lombok notes
文章目录
@Getter and @Setter
https://projectlombok.org/features/GetterSetter
作用目标
- 类
- 字段
生成 gettter 名称
普通类型
- foo –> getFool()
boolean
- foo –> isFool()
javadoc 转换
@param @return 会被自动转换到生成代码的对应位置
原始代码
1 2 3 4 5 6 7/** ,* Age of the person. Water is wet. ,* ,* @param age New value for this person's age. Sky is blue. ,* @return The current value of this person's age. Circles are round. ,*/ @Getter @Setter private int age = 10;生成代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17/** ,* Age of the person. Water is wet. ,* ,* @return The current value of this person's age. Circles are round. ,*/ public int getAge() { return age; } /** ,* Age of the person. Water is wet. ,* ,* @param age New value for this person's age. Sky is blue. ,*/ public void setAge(int age) { this.age = age; }
生成代码的访问属性修改
使用 AccessLevel.PROTECTED 枚举类型 —> protected
原始代码
1 2 3 4 5 6 7 8/** ,* Name of the person. ,* -- SETTER -- ,* Changes the name of this person. ,* ,* @param name The new value. ,*/ @Setter(AccessLevel.PROTECTED) private String name;生成代码
1 2 3 4 5 6 7 8/** ,* Changes the name of this person. ,* ,* @param name The new value. ,*/ protected void setName(String name) { this.name = name; }
在生成代码上,放置注释
- 正在试验的功能
修饰生成方法
- eg: onMethod=@__({@AnnotationsHere})
修饰生成方法的参数
- eg: onParam=@__({@AnnotationsHere})
@NonNull
禁用空指针
修饰对象
- 方法的参数
- 类的字段
https://projectlombok.org/features/NonNull
原理
- 在生成的代码中,添加空指针抛出异常代码
使用
1 2 3 4public NonNullExample(@NonNull Person person) { super("Hello"); this.name = person.getName(); }
@Cleanup
自动关闭文件
- 原理:自动调用 close()
@EqualsAndHashCode
为自动生成的 equals 方法 和 hashCode 方法
- 还可以,自定义排除一些 non-static 和 non-transient 字段
注释的属性
- exclude
- include
callSuper
- 决定,是否使用 super.equals() 和 super.hashCode()
@ToString
自动生成 toString() 方法
处理构造函数
注解属性
staticName: 除指定构造函数外,还生成使用构造函数制作的工厂函数
- staticName="of": 指定工厂函数的名称是 of
- 注意:
这时生成的构造函数,访问权限是 "private"
onConstructor=@__({@AnnotationsHere})
- 指定标注到生成的构造函数上的注解
access = AccessLevel.PROTECTED
- 指定访问权限
@NoArgsConstructor
- 有字段为 final, 报错
@RequiredArgsConstructor
final 字段 和 non-null 字段
- non-null 字段: 被@NotNull 标注的字段
@AllArgsConstructor
- 所有字段
@Data
相当于 同时使用@ToString, @EqualsAndHashCode, @Getter[on all fileds], @Setter[on all non-final fileds], @RequiredArgsConstructor 等
@Value
用于不可变对象, 相比于@Data
- 生成字段使用 private 和 final 修饰
- 只有 getter, 没有 settter
https://projectlombok.org/features/Value
- @Value is shorthand for: final, @ToString, @EqualsAndHashCode, @AllArgsConstructor, @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE), @Getter
作用原理
在 javac 阶段起作用
文章作者
上次更新 2022-03-07 (de34a70)