简介
Lombok可用例帮助开发人员消除Java的冗长代码,尤其是对于简单的Java对象(POJO),它通过注释实现这个目的。
intellij安装
- 首先通过ideal插件中心进行安装,找到lombok的插件
- 导入lonbok包到maven工程
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
Lombok注解解释
@Data
此注解在类上,提供类所有属性的get和set方法。同时还提供 equals,canEqual,hashCode,toString等方法
@Setter/@Getter
- 注解在属性上,为单个属性提供set/get方法
- 注解在类上,为该类所有属性都提供set/get方法,都提供默认构造方法
@Log4j
在 类上注解属性名为log的log4j对象,提供默认构造方法。
@AllArgsConstructor
注解在类上,提供全参的构造方法,加了这个注解后,类中不提供默认构造方法了。
### @AllArgsConstructor
public class LomBokData {
private String name;
private Integer age;
}
转换成下面代码
public class TestLombok {
public void testLomBok(){
LomBokData lomBokData = new LomBokData("dankun",20);
}
}
@NoArgsConstructor
注解在 类 上;为类提供一个无参的构造方法。
@EqualsAndHashCode
注解在 类 上, 可以生成 equals、canEqual、hashCode 方法。
@EqualsAndHashCode
public class LomBokData {
}
转换成下面代码
public class LomBokData {
public LomBokData() {
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof LomBokData)) {
return false;
} else {
LomBokData other = (LomBokData)o;
return other.canEqual(this);
}
}
protected boolean canEqual(Object other) {
return other instanceof LomBokData;
}
public int hashCode() {
int result = 1;
return result;
}
}
@NonNull
注解在属性上,会自动产生一个关于此参数的非空校验。如果参数为空,则抛出一个空指针的异常,也会有一个默认的无参构造方法。
@Value
LomBok的@Value和Spring自带的 @Value注解不一样。Spring中的@Value是注解在方法或者字段上
LomBok的@Value注解在类上,会生成含所有参数的构造方法,get 方法,此外还提供了equals、hashCode、toString 方法。
@Value
public class LomBokData {
private String name;
}
转换成下面代码
public final class LomBokData {
private final String name;
public LomBokData(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof LomBokData)) {
return false;
} else {
LomBokData other = (LomBokData)o;
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
return true;
}
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $name = this.getName();
int result = result * 59 + ($name == null ? 43 : $name.hashCode());
return result;
}
public String toString() {
return "LomBokData(name=" + this.getName() + ")";
}
}
@SneakyThrows
用于方法之上,可以将方法使用try-catch语句进行包裹,捕获异常并在 catch 中用 Lombok.sneakyThrow(e) 把异常抛出,可以使用 @SneakyThrows(Exception.class) 的形式指定抛出哪种异常,也会生成默认的构造方法。
public class LomBokData {
@SneakyThrows
public void getName(){
System.out.println("dankun");
}
}
生成的代码
public class LomBokData {
public LomBokData() {
}
public void getName() {
try {
System.out.println("dankun");
} catch (Throwable var2) {
throw var2;
}
}
}