一蛉腌、Lombok是什么阱飘?
如果想自己完成從官網(wǎng)學(xué)習(xí)可以點擊:https://projectlombok.org/。功能和AutoValue很類似。使用Lombok可以方便的生成setter斩披、getter端姚、equals晕粪、hashcode、toString等方法渐裸,代碼看起來十分的優(yōu)雅巫湘。
二、Android上如何集成
1.工程下面新建lombok.config文件昏鹃。文件內(nèi)容是:
lombok.anyConstructor.suppressConstructorProperties=true
2.在app的build.gradle中添加依賴:
dependencies {
```
compileOnly "org.projectlombok:lombok:1.16.18"
implementation 'org.glassfish:javax.annotation:10.0-b28'
}
3.在Android Studio中安裝lombok插件
4.錯誤修復(fù)
javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
三尚氛、使用
通過上面的步驟,就已經(jīng)在Android Studio中集成好了Lombok洞渤,接下來就是使用阅嘶。可以有哪些關(guān)鍵字注解可以參考官方文檔:https://projectlombok.org/features/all
val
Finally! Hassle-free final local variables.
var
Mutably! Hassle-free local variables.
@NonNull
or: How I learned to stop worrying and love the NullPointerException.
@Cleanup
Automatic resource management: Call your close()
methods safely with no hassle.
@Getter/@Setter
Never write public int getFoo() {return foo;}
again.
@ToString
No need to start a debugger to see your fields: Just let lombok generate a toString
for you!
@EqualsAndHashCode
Equality made easy: Generates hashCode
and equals
implementations from the fields of your object..
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
Constructors made to order: Generates constructors that take no arguments, one argument per final / non-nullfield, or one argument for every field.
@Data
All together now: A shortcut for @ToString
, @EqualsAndHashCode
, @Getter
on all fields, and @Setter
on all non-final fields, and @RequiredArgsConstructor
!
@Value
Immutable classes made very easy.
@Builder
... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!
@SneakyThrows
To boldly throw checked exceptions where no one has thrown them before!
@Synchronized
synchronized
done right: Don't expose your locks.
@With
Immutable 'setters' - methods that create a clone but with one changed field.
@Getter(lazy=true)
Laziness is a virtue!
@Log
Captain's Log, stardate 24435.7: "What was that line again?"
experimental
Head to the lab: The new stuff we're working on.
但是上面的很多注解不是我使用的初衷载迄,例如@NonNull這種Android的support包里面都有讯柔。我想用的是@Data這種的。比如我寫了一個實體類护昧,我可以加個注解就生成了get/set/tostring/構(gòu)造函數(shù)等魂迄。
package com.stormdzh.androidlombok.entity;
import lombok.Data;
/**
* @Description: 測試實體類
* @Author: dzh
* @CreateDate: 2020-11-29 22:05
*/
@Data
public class User {
private String name;
private String avatar;
}
上面的代碼加個@Data注解之后,就有有了以下的方法惋耙,這就很方便了捣炬。
四、總結(jié)
集成和簡單使用已經(jīng)總結(jié)了绽榛,其余的那些關(guān)鍵字可以看看官方的文檔湿酸。有特殊的需求可以在研究下,官網(wǎng)上也有很多實例代碼灭美。