一、Lombok是什么?
如果想自己完成从官网学习可以点击:https://projectlombok.org/。功能和AutoValue很类似。使用Lombok可以方便的生成setter、getter、equals、hashcode、toString等方法,代码看起来十分的优雅。
二、Android上如何集成
1.工程下面新建lombok.config文件。文件内容是:
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.错误修复
javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
三、使用
通过上面的步骤,就已经在Android Studio中集成好了Lombok,接下来就是使用。可以有哪些关键字注解可以参考官方文档: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/构造函数等。
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注解之后,就有有了以下的方法,这就很方便了。
四、总结
集成和简单使用已经总结了,其余的那些关键字可以看看官方的文档。有特殊的需求可以在研究下,官网上也有很多实例代码。