五、Lombok 注解详解(3)
5,@NoArgsConstructor
注解在类上,为类提供一个无参的构造方法。
注意:
- 当类中有 final 字段没有被初始化时,编译器会报错,此时可用 @NoArgsConstructor(force = true),然后就会为没有初始化的 final 字段设置默认值 0 / false / null。
- 对于具有约束的字段(例如 @NonNull 字段),不会生成检查或分配,因此请注意,正确初始化这些字段之前,这些约束无效。
1 // 使用注解
2 @NoArgsConstructor
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 public Shape(){
18 }
19 }
6,@AllArgsConstructor
(1)注解在类上,为类提供一个全参的构造方法。
(2)默认生成的方法是 public 的,如果要修改方法修饰符可以设置 AccessLevel 的值。
- 例如:@Getter(access = AccessLevel.PROTECTED)
1 // 使用注解
2 @AllArgsConstructor(access = AccessLevel.PROTECTED)
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 protected Shape(int x, double y, String name){
18 this.x = x;
19 this.y = y;
20 this.name = name;
21 }
22 }
7,@RequiredArgsConstructor
(1)注解在类上,会生成构造方法(可能带参数也可能不带参数)。
注意:如果带参数,这参数只能是以 final 修饰的未经初始化的字段或者是以 @NonNull 注解的未经初始化的字段。
(2)该注解还可以用 @RequiredArgsConstructor(staticName="methodName") 的形式生成一个指定名称的静态方法,返回一个调用相应的构造方法产生的对象
1 // 使用注解
2 @RequiredArgsConstructor(staticName = "hangge")
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 public Shape(double y, String name){
18 this.y = y;
19 this.name = name;
20 }
21
22 public static Shape hangge(double y, String name){
23 return new Shape(y, name);
24 }
25 }