https://www.hangge.com/blog/cache/detail_2493.html
5,@NoArgsConstructor
- 当类中有 final 字段没有被初始化时,编译器会报错,此时可用 @NoArgsConstructor(force = true),然后就会为没有初始化的 final 字段设置默认值 0 / false / null。
- 对于具有约束的字段(例如 @NonNull 字段),不会生成检查或分配,因此请注意,正确初始化这些字段之前,这些约束无效。
// 使用注解 @NoArgsConstructor public class Shape { private int x; @NonNull private double y; @NonNull private String name; } // 不使用注解 public class Shape { private int x; private double y; private String name; public Shape(){ } }
6,@AllArgsConstructor
- 例如:@Getter(access = AccessLevel.PROTECTED)
// 使用注解 @AllArgsConstructor(access = AccessLevel.PROTECTED) public class Shape { private int x; @NonNull private double y; @NonNull private String name; } // 不使用注解 public class Shape { private int x; private double y; private String name; protected Shape(int x, double y, String name){ this.x = x; this.y = y; this.name = name; } }
7,@RequiredArgsConstructor
// 使用注解 @RequiredArgsConstructor(staticName = "hangge") public class Shape { private int x; @NonNull private double y; @NonNull private String name; } // 不使用注解 public class Shape { private int x; private double y; private String name; public Shape(double y, String name){ this.y = y; this.name = name; } public static Shape hangge(double y, String name){ return new Shape(y, name); } }
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2493.html