Lombok @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor注解
@NoArgsConstructor
@NoArgsConstructor用来指定无参数构造器,如果设置@NoArgsConstructor(force = true)
,参数意味着所有final字段被初始化为 0 / false / null。
@RequiredArgsConstructor
@RequiredArgsConstructor每个需要特殊处理的字段生成一个带有相应参数的构造函数。生成的构造方法是private,如何想要对外提供使用可以使用staticName选项生成一个static方法,即@RequiredArgsConstructor(staticName="of")
。
@AllArgsConstructor
@AllArgsConstructor
为类中的每个字段生成一个带有1个参数的构造函数,对标记为的字段@NonNull
对进行空参校验。
对比12
使用了lombok
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
@NoArgsConstructor
public static class NoArgsExample {
@NonNull private String field;
}
}
未使用lombok
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
private ConstructorExample(T description) {
if (description == null) throw new NullPointerException("description");
this.description = description;
}
public static <T> ConstructorExample<T> of(T description) {
return new ConstructorExample<T>(description);
}
@java.beans.ConstructorProperties({"x", "y", "description"})
protected ConstructorExample(int x, int y, T description) {
if (description == null) throw new NullPointerException("description");
this.x = x;
this.y = y;
this.description = description;
}
public static class NoArgsExample {
@NonNull private String field;
public NoArgsExample() {
}
}
}