@Data 的作用?
使用这个注解,就不用再去手写Getter,Setter,equals,canEqual,hasCode,toString等方法了,注解后在编译时会自动加进去。
@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor
@NoArgsConstructor:生成无参构造函数
@RequiredArgsConstructor:生成一个构造函数,并对打了@NonNull的参数进行NullPointer检查 (这里有坑?为啥?)
例如:
// 源代码
@RequiredArgsConstructor(staticName = "of")
class Car{
@NonNull
private String origin;
@NonNull
private String model;
}
// 编译后代码
class Car{
@NonNull
private String origin;
@NonNull
private String model;
// 省略get、set方法
private Car(@NonNull String origin, @NonNull String model) {
if (origin == null) {
throw new NullPointerException("origin is marked @NonNull but is null");
} else {
this.origin = origin;
}
if (model == null) {
throw new NullPointerException("model is marked @NonNull but is null");
} else {
this.model = model;
}
}
public static Car of(@NonNull String origin, @NonNull String model) {
return new Car(origin, model);
}
}
@AllArgsConstructor:生成全参构造函数
@NoArgsConstructor will generate a constructor with no parameters. If
this is not possible (because of final fields), a compiler error will
result instead, unless @NoArgsConstructor(force = true) is used, then
all final fields are initialized with 0 / false / null. For fields
with constraints, such as @NonNull fields, no check is generated,so be
aware that these constraints will generally not be fulfilled until
those fields are properly initialized later. This annotation is useful
primarily in combination with either @Data or one of the other
constructor generating annotations.
lombok还有什么常见用法?
上面的@Data、@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor都是lombok的注解。
其他还有:
@builder有什么用?
当一个类的属性很多,但构造时只需要其中几个属性时,更方便。
@builder的原理是什么
@builder自动实现了以下原生的builder模式
class Car{
private String origin;
private String model;
private Car(String model){
this.model = model;
}
private Car(Builder builder){
this.origin = builder.origin;
this.model = builder.model;
}
public static Car of(String model){
return new Car(model);
}
public static Builder builder(){
return new Builder();
}
public static class Builder{
private String origin;
private String model;
public Builder origin(String origin){
this.origin = origin;
return this;
}
public Builder model(String model){
this.model = model;
return this;
}
public Car build(){
return new Car(this);
}
}
}