Lombok
使用项目lombok减少样板代码
官网地址:
https://objectcomputing.com/resources/publications/sett/january-2010-reducing-boilerplate-code-with-project-lombok
Lombok依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>projectlombok.org</id>
<url>http://projectlombok.org/mavenrepo</url>
</repository>
</repositories>
常用注解
@Data
- setter
- getter(boolean类型生成的是isXX而不是getXX)
- equals
- hashcode
@ToString
- toString
// callSuper是否包含父类字段,默认false
// exclude 排除字段
@ToString(callSuper=true,exclude="someExcludedField")
public class Foo extends Bar {
private boolean someBoolean = true;
private String someStringField;
private float someExcludedField;
}
@NonNull
判断字段是否为空,感觉意义不大,通常判断除了null,还会判是不是空串,或者集合元素为空
@AllArgsConstructor
public class LombokDemo {
@NonNull
@Setter
@Getter
private String name;
@NonNull
@Setter
@Getter
private List<String> strings;
}
等同于
public class LombokDemo {
@NonNull
private String name;
@NonNull
private List<String> strings;
// 使用lombok设置构造方法
public LombokDemo(@NonNull String name, @NonNull List<String> strings) {
if (name == null) {
throw new NullPointerException("name is marked non-null but is null");
} else if (strings == null) {
throw new NullPointerException("strings is marked non-null but is null");
} else {
this.name = name;
this.strings = strings;
}
}
public void setName(@NonNull String name) {
if (name == null) {
throw new NullPointerException("name is marked non-null but is null");
} else {
this.name = name;
}
}
@NonNull
public String getName() {
return this.name;
}
public void setStrings(@NonNull List<String> strings) {
if (strings == null) {
throw new NullPointerException("strings is marked non-null but is null");
} else {
this.strings = strings;
}
}
@NonNull
public List<String> getStrings() {
return this.strings;
}
}
@EqualsAndHashCode
- equals
- hashcode
@Cleanup
- 关闭资源,默认方法close
@SneakyThrows
public static void main(String[] args) {
@Cleanup
FileInputStream in = new FileInputStream("");
}
等价于
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("");
if (Collections.singletonList(in).get(0) != null) {
in.close();
}
} catch (Throwable var2) {
throw var2;
}
}
@Synchronized
- synchronized 同步块
@Synchronized
public void add(String str){
strings.add(str);
}
等价于
public void add(String str) {
synchronized(this.$lock) {
this.strings.add(str);
}
}
@SneakyThrows
- 无需声明检查异常
@SneakyThrows
public void poll(){
throw new Exception();
}
等价于
public void poll() {
try {
throw new Exception();
} catch (Throwable var2) {
throw var2;
}
}