五、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 }

最新文章

  1. NS2中修改载波侦听范围和传输范围
  2. ThroughRain第二次冲刺(每天更新
  3. 四 mybatis开发dao的方法
  4. meta是什么意思?
  5. the partition number
  6. ThinkPHP删除栏目(多)
  7. App Inventor2项目部署到本地
  8. GDI与GDI+性能比较
  9. Android开发之如何避免ANR(Keeping Your App Responsive)
  10. ES6 原始类型 Symbol
  11. 小技巧css解决移动端ios不兼容position:fixed属性,无需插件
  12. no matching editors or conversion strategy found
  13. Spring boot实现自定义拦截器
  14. 洛谷 P5089: CodeForces #500 (Div. 1) B / 1012B : Chemical table
  15. 练习题 --- 写出5种css定位语法
  16. 从0开始学习 GITHUB 系列之「GIT 进阶」【转】
  17. git squash 和 git rebase
  18. Tempdb--查看tempdb使用的脚本
  19. Win10系统中新增的快捷键,做个记录
  20. bootstrap基本用法

热门文章

  1. 央行DR007在哪里查看
  2. 关于活动目录AD(域)的相关配置(已更新8.31)
  3. centos 绑定多ip
  4. Zookeeper ZAB协议-Leader&Followe 对象创建和启动源码解析
  5. Respecting causality is all you need for training physics-informed neural networks
  6. Mosquitto安装与部署
  7. Mac聚焦搜索无法搜索应用问题处理
  8. 更改svn地址
  9. vue _DAY1
  10. 常见DOS命令及应用