Android上使用Lombok
简介
最近几天尝试了一把后端的工作,发现后端同学使用了一个第三库——Lombok,用了一下,感觉还不错,特来介绍一下,感觉和以前介绍过的AutoValue挺像的。
Lombok 官网上面有个几分钟的视频,接单介绍了Lombok的用途,使用方法很简单,只需要依赖对应的jar文件,然后在对应的Java文件上使用注解即可。
先看个例子,下面是常见的一个Java一个实体类,含有field、setter、getter、equals、hashcode、toString方法。
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (id != user.id) return false;
return name != null ? name.equals(user.name) : user.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
如果使用了Lombok,就很简单了,直接定义好字段,然后添加一个注解@Data
即可,其他方法,工具自动生成,虽然上面的方法我们也是用工具生成的,但是如果要添加或者删除字段,还是要修改代码的,如果直接使用注解的方式,那么还是简单的,无需修改任何方法。
@Data
public class UserLombok {
private int id;
private String name;
}
注解简介
Lombok 主要使用就是通过添加注解,来自动生成代码,主要包含两类,一种是Stable类型,一种是Experimental。前面表示稳定的注解,后面表示实验类型的,可能会被移除。本文主要介绍Stable类型,Experimental由于使用较少,不做讲解。
Stable
- val
Finally! Hassle-free final 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.
- @Getter(lazy=true)
Laziness is a virtue!
- @Log
Captain’s Log, stardate 24435.7: “What was that line again?”
Experimental
- var
Modifiable local variables with a type inferred by assigning value.
- @Accessors
A more fluent API for getters and setters.
- @ExtensionMethod
Annoying API? Fix it yourself: Add new methods to existing types!
- @FieldDefaults
New default field modifiers for the 21st century.
- @Delegate
Don’t lose your comp