Java Lombok

1、Lombok简介

Lombok 是一款 Java开发插件,使得 Java 开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的 Java 模型对象(POJO)。在开发环境中使用 Lombok插件后,Java 开发人员可以节省出重复构建,诸如 hashCodeequals 这样的方法以及各种业务对象模型的 accessortoString 等方法的大量时间。对于这些方法,Lombok 能够在编译源代码期间自动生成这些方法,但并不会像反射那样降低程序的性能。

2、Lombok安装

构建工具

Gradle

在 build.gradle 文件中添加 Lombok 依赖:

  1. dependencies {
  2. compileOnly 'org.projectlombok:lombok:1.18.10'
  3. annotationProcessor 'org.projectlombok:lombok:1.18.10'
  4. }

Maven

在 Maven 项目的 pom.xml 文件中添加 Lombok 依赖:

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.10</version>
  5. <scope>provided</scope>
  6. </dependency>

Ant

假设在 lib 目录中已经存在 lombok.jar,然后设置 javac 任务:

  1. <javac srcdir="src" destdir="build" source="1.8">
  2. <classpath location="lib/lombok.jar" />
  3. </javac>

IDE

由于 Lombok 仅在编译阶段生成代码,所以使用 Lombok 注解的源代码,在 IDE 中会被高亮显示错误,针对这个问题可以通过安装 IDE 对应的插件来解决。这里不详细展开,具体的安装方式可以参考:
https://www.baeldung.com/lombok-ide

3、Lombok 详解

注意:以下示例所使用的 Lombok 版本是 1.18.10

3.1 @Getter and @Setter

可以使用 @Getter@Setter 注释任何类或字段,Lombok 会自动生成默认的 getter/setter 方法。

@Getter 注解

  1. @Target({ElementType.FIELD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Getter {
  4. // 若getter方法非public的话,可以设置可访问级别
  5. lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
  6. AnyAnnotation[] onMethod() default {};
  7. // 是否启用延迟初始化
  8. boolean lazy() default false;
  9. }

@Setter

  1. @Target({ElementType.FIELD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Setter {
  4. // 若setter方法非public的话,可以设置可访问级别
  5. lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
  6. AnyAnnotation[] onMethod() default {};
  7. AnyAnnotation[] onParam() default {};
  8. }

使用示例

  1. @Getter
  2. @Setter
  3. public class GetterAndSetterDemo {
  4. String firstName;
  5. String lastName;
  6. LocalDate dateOfBirth;
  7. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class GetterAndSetterDemo {
  2. String firstName;
  3. String lastName;
  4. LocalDate dateOfBirth;
  5. public GetterAndSetterDemo() {
  6. }
  7. // 省略其它setter和getter方法
  8. public String getFirstName() {
  9. return this.firstName;
  10. }
  11. public void setFirstName(String firstName) {
  12. this.firstName = firstName;
  13. }
  14. }

Lazy Getter

@Getter 注解支持一个 lazy 属性,该属性默认为 false。当设置为 true 时,会启用延迟初始化,即当首次调用 getter 方法时才进行初始化。
示例

  1. public class LazyGetterDemo {
  2. public static void main(String[] args) {
  3. LazyGetterDemo m = new LazyGetterDemo();
  4. System.out.println("Main instance is created");
  5. m.getLazy();
  6. }
  7. @Getter
  8. private final String notLazy = createValue("not lazy");
  9. @Getter(lazy = true)
  10. private final String lazy = createValue("lazy");
  11. private String createValue(String name) {
  12. System.out.println("createValue(" + name + ")");
  13. return null;
  14. }
  15. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class LazyGetterDemo {
  2. private final String notLazy = this.createValue("not lazy");
  3. private final AtomicReference<Object> lazy = new AtomicReference();
  4. // 已省略部分代码
  5. public String getNotLazy() {
  6. return this.notLazy;
  7. }
  8. public String getLazy() {
  9. Object value = this.lazy.get();
  10. if (value == null) {
  11. synchronized(this.lazy) {
  12. value = this.lazy.get();
  13. if (value == null) {
  14. String actualValue = this.createValue("lazy");
  15. value = actualValue == null ? this.lazy : actualValue;
  16. this.lazy.set(value);
  17. }
  18. }
  19. }
  20. return (String)((String)(value == this.lazy ? null : value));
  21. }
  22. }

通过以上代码可知,调用 getLazy 方法时,若发现 value 为 null,则会在同步代码块中执行初始化操作。

3.2 Constructor Annotations

@NoArgsConstructor

使用 @NoArgsConstructor 注解可以为指定类,生成默认的构造函数,@NoArgsConstructor 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface NoArgsConstructor {
  4. // 若设置该属性,将会生成一个私有的构造函数且生成一个staticName指定的静态方法
  5. String staticName() default "";
  6. AnyAnnotation[] onConstructor() default {};
  7. // 设置生成构造函数的访问级别,默认是public
  8. AccessLevel access() default lombok.AccessLevel.PUBLIC;
  9. // 若设置为true,则初始化所有final的字段为0/null/false
  10. boolean force() default false;
  11. }

示例

  1. @NoArgsConstructor(staticName = "getInstance")
  2. public class NoArgsConstructorDemo {
  3. private long id;
  4. private String name;
  5. private int age;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class NoArgsConstructorDemo {
  2. private long id;
  3. private String name;
  4. private int age;
  5. private NoArgsConstructorDemo() {
  6. }
  7. public static NoArgsConstructorDemo getInstance() {
  8. return new NoArgsConstructorDemo();
  9. }
  10. }

@AllArgsConstructor

使用 @AllArgsConstructor 注解可以为指定类,生成包含所有成员的构造函数,@AllArgsConstructor 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface AllArgsConstructor {
  4. // 若设置该属性,将会生成一个私有的构造函数且生成一个staticName指定的静态方法
  5. String staticName() default "";
  6. AnyAnnotation[] onConstructor() default {};
  7. // 设置生成构造函数的访问级别,默认是public
  8. AccessLevel access() default lombok.AccessLevel.PUBLIC;
  9. }

示例

  1. @AllArgsConstructor
  2. public class AllArgsConstructorDemo {
  3. private long id;
  4. private String name;
  5. private int age;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class AllArgsConstructorDemo {
  2. private long id;
  3. private String name;
  4. private int age;
  5. public AllArgsConstructorDemo(long id, String name, int age) {
  6. this.id = id;
  7. this.name = name;
  8. this.age = age;
  9. }
  10. }

@RequiredArgsConstructor

使用 @RequiredArgsConstructor 注解可以为指定类必需初始化的成员变量,如 final 成员变量,生成对应的构造函数,@RequiredArgsConstructor 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface RequiredArgsConstructor {
  4. // 若设置该属性,将会生成一个私有的构造函数且生成一个staticName指定的静态方法
  5. String staticName() default "";
  6. AnyAnnotation[] onConstructor() default {};
  7. // 设置生成构造函数的访问级别,默认是public
  8. AccessLevel access() default lombok.AccessLevel.PUBLIC;
  9. }

示例

  1. @RequiredArgsConstructor
  2. public class RequiredArgsConstructorDemo {
  3. private final long id;
  4. private String name;
  5. private int age;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class RequiredArgsConstructorDemo {
  2. private final long id;
  3. private String name;
  4. private int age;
  5. public RequiredArgsConstructorDemo(long id) {
  6. this.id = id;
  7. }
  8. }

3.3 @EqualsAndHashCode

使用 @EqualsAndHashCode 注解可以为指定类生成 equalshashCode 方法, @EqualsAndHashCode 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface EqualsAndHashCode {
  4. // 指定在生成的equals和hashCode方法中需要排除的字段列表
  5. String[] exclude() default {};
  6. // 显式列出用于identity的字段,一般情况下non-static,non-transient字段会被用于identity
  7. String[] of() default {};
  8. // 标识在执行字段计算前,是否调用父类的equals和hashCode方法
  9. boolean callSuper() default false;
  10. boolean doNotUseGetters() default false;
  11. AnyAnnotation[] onParam() default {};
  12. @Deprecated
  13. @Retention(RetentionPolicy.SOURCE)
  14. @Target({})
  15. @interface AnyAnnotation {}
  16. @Target(ElementType.FIELD)
  17. @Retention(RetentionPolicy.SOURCE)
  18. public @interface Exclude {}
  19. @Target({ElementType.FIELD, ElementType.METHOD})
  20. @Retention(RetentionPolicy.SOURCE)
  21. public @interface Include {
  22. String replaces() default "";
  23. }
  24. }

示例

  1. @EqualsAndHashCode
  2. public class EqualsAndHashCodeDemo {
  3. String firstName;
  4. String lastName;
  5. LocalDate dateOfBirth;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class EqualsAndHashCodeDemo {
  2. String firstName;
  3. String lastName;
  4. LocalDate dateOfBirth;
  5. public EqualsAndHashCodeDemo() {
  6. }
  7. public boolean equals(Object o) {
  8. if (o == this) {
  9. return true;
  10. } else if (!(o instanceof EqualsAndHashCodeDemo)) {
  11. return false;
  12. } else {
  13. EqualsAndHashCodeDemo other = (EqualsAndHashCodeDemo)o;
  14. if (!other.canEqual(this)) {
  15. return false;
  16. } else {
  17. // 已省略大量代码
  18. }
  19. }
  20. public int hashCode() {
  21. int PRIME = true;
  22. int result = 1;
  23. Object $firstName = this.firstName;
  24. int result = result * 59 + ($firstName == null ? 43 : $firstName.hashCode());
  25. Object $lastName = this.lastName;
  26. result = result * 59 + ($lastName == null ? 43 : $lastName.hashCode());
  27. Object $dateOfBirth = this.dateOfBirth;
  28. result = result * 59 + ($dateOfBirth == null ? 43 : $dateOfBirth.hashCode());
  29. return result;
  30. }
  31. }

3.4 @ToString

使用 @ToString 注解可以为指定类生成 toString 方法, @ToString 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface ToString {
  4. // 打印输出时是否包含字段的名称
  5. boolean includeFieldNames() default true;
  6. // 列出打印输出时,需要排除的字段列表
  7. String[] exclude() default {};
  8. // 显式的列出需要打印输出的字段列表
  9. String[] of() default {};
  10. // 打印输出的结果中是否包含父类的toString方法的返回结果
  11. boolean callSuper() default false;
  12. boolean doNotUseGetters() default false;
  13. boolean onlyExplicitlyIncluded() default false;
  14. @Target(ElementType.FIELD)
  15. @Retention(RetentionPolicy.SOURCE)
  16. public @interface Exclude {}
  17. @Target({ElementType.FIELD, ElementType.METHOD})
  18. @Retention(RetentionPolicy.SOURCE)
  19. public @interface Include {
  20. int rank() default 0;
  21. String name() default "";
  22. }
  23. }

示例

  1. @ToString(exclude = {"dateOfBirth"})
  2. public class ToStringDemo {
  3. String firstName;
  4. String lastName;
  5. LocalDate dateOfBirth;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class ToStringDemo {
  2. String firstName;
  3. String lastName;
  4. LocalDate dateOfBirth;
  5. public ToStringDemo() {
  6. }
  7. public String toString() {
  8. return "ToStringDemo(firstName=" + this.firstName + ", lastName=" +
  9. this.lastName + ")";
  10. }
  11. }

3.5 @Data

@Data 注解与同时使用以下的注解的效果是一样的:

  1. @ToString
  2. @Getter
  3. @Setter
  4. @RequiredArgsConstructor
  5. @EqualsAndHashCode

@Data 注解的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Data {
  4. String staticConstructor() default "";
  5. }

示例

  1. @Data
  2. public class DataDemo {
  3. private Long id;
  4. private String summary;
  5. private String description;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class DataDemo {
  2. private Long id;
  3. private String summary;
  4. private String description;
  5. public DataDemo() {
  6. }
  7. // 省略summary和description成员属性的setter和getter方法
  8. public Long getId() {
  9. return this.id;
  10. }
  11. public void setId(Long id) {
  12. this.id = id;
  13. }
  14. public boolean equals(Object o) {
  15. if (o == this) {
  16. return true;
  17. } else if (!(o instanceof DataDemo)) {
  18. return false;
  19. } else {
  20. DataDemo other = (DataDemo)o;
  21. if (!other.canEqual(this)) {
  22. return false;
  23. } else {
  24. // 已省略大量代码
  25. }
  26. }
  27. }
  28. protected boolean canEqual(Object other) {
  29. return other instanceof DataDemo;
  30. }
  31. public int hashCode() {
  32. int PRIME = true;
  33. int result = 1;
  34. Object $id = this.getId();
  35. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
  36. Object $summary = this.getSummary();
  37. result = result * 59 + ($summary == null ? 43 : $summary.hashCode());
  38. Object $description = this.getDescription();
  39. result = result * 59 + ($description == null ? 43 : $description.hashCode());
  40. return result;
  41. }
  42. public String toString() {
  43. return "DataDemo(id=" + this.getId() + ", summary=" + this.getSummary() + ", description=" + this.getDescription() + ")";
  44. }
  45. }

3.6 @Log

若将 @Log 的变体放在类上(适用于日志记录系统的任何一种),之后,将拥有一个静态的 final log 字段,然后就可以使用该字段来输出日志。

  1. @Log
  2. private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
  3. @Log4j
  4. private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);
  5. @Log4j2
  6. private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
  7. @Slf4j
  8. private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
  9. @XSlf4j
  10. private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
  11. @CommonsLog
  12. private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);

3.7 @Synchronized

@Synchronized 是同步方法修饰符的更安全的变体。与 synchronized 一样,该注解只能应用在静态和实例方法上。它的操作类似于 synchronized 关键字,但是它锁定在不同的对象上。synchronized 关键字应用在实例方法时,锁定的是 this 对象,而应用在静态方法上锁定的是类对象。对于 @Synchronized 注解声明的方法来说,它锁定的是 或lock。@Synchronized 注解的定义如下:

  1. @Target(ElementType.METHOD)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Synchronized {
  4. // 指定锁定的字段名称
  5. String value() default "";
  6. }

示例

  1. public class SynchronizedDemo {
  2. private final Object readLock = new Object();
  3. @Synchronized
  4. public static void hello() {
  5. System.out.println("world");
  6. }
  7. @Synchronized
  8. public int answerToLife() {
  9. return 42;
  10. }
  11. @Synchronized("readLock")
  12. public void foo() {
  13. System.out.println("bar");
  14. }
  15. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class SynchronizedDemo {
  2. private static final Object $LOCK = new Object[0];
  3. private final Object $lock = new Object[0];
  4. private final Object readLock = new Object();
  5. public SynchronizedDemo() {
  6. }
  7. public static void hello() {
  8. synchronized($LOCK) {
  9. System.out.println("world");
  10. }
  11. }
  12. public int answerToLife() {
  13. synchronized(this.$lock) {
  14. return 42;
  15. }
  16. }
  17. public void foo() {
  18. synchronized(this.readLock) {
  19. System.out.println("bar");
  20. }
  21. }
  22. }

3.8 @Builder

使用 @Builder 注解可以为指定类实现建造者模式,该注解可以放在类、构造函数或方法上。@Builder 注解的定义如下:

  1. @Target({TYPE, METHOD, CONSTRUCTOR})
  2. @Retention(SOURCE)
  3. public @interface Builder {
  4. @Target(FIELD)
  5. @Retention(SOURCE)
  6. public @interface Default {}
  7. // 创建新的builder实例的方法名称
  8. String builderMethodName() default "builder";
  9. // 创建Builder注解类对应实例的方法名称
  10. String buildMethodName() default "build";
  11. // builder类的名称
  12. String builderClassName() default "";
  13. boolean toBuilder() default false;
  14. AccessLevel access() default lombok.AccessLevel.PUBLIC;
  15. @Target({FIELD, PARAMETER})
  16. @Retention(SOURCE)
  17. public @interface ObtainVia {
  18. String field() default "";
  19. String method() default "";
  20. boolean isStatic() default false;
  21. }
  22. }

示例

  1. @Builder
  2. public class BuilderDemo {
  3. private final String firstname;
  4. private final String lastname;
  5. private final String email;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class BuilderDemo {
  2. private final String firstname;
  3. private final String lastname;
  4. private final String email;
  5. BuilderDemo(String firstname, String lastname, String email) {
  6. this.firstname = firstname;
  7. this.lastname = lastname;
  8. this.email = email;
  9. }
  10. public static BuilderDemo.BuilderDemoBuilder builder() {
  11. return new BuilderDemo.BuilderDemoBuilder();
  12. }
  13. public static class BuilderDemoBuilder {
  14. private String firstname;
  15. private String lastname;
  16. private String email;
  17. BuilderDemoBuilder() {
  18. }
  19. public BuilderDemo.BuilderDemoBuilder firstname(String firstname) {
  20. this.firstname = firstname;
  21. return this;
  22. }
  23. public BuilderDemo.BuilderDemoBuilder lastname(String lastname) {
  24. this.lastname = lastname;
  25. return this;
  26. }
  27. public BuilderDemo.BuilderDemoBuilder email(String email) {
  28. this.email = email;
  29. return this;
  30. }
  31. public BuilderDemo build() {
  32. return new BuilderDemo(this.firstname, this.lastname, this.email);
  33. }
  34. public String toString() {
  35. return "BuilderDemo.BuilderDemoBuilder(firstname=" + this.firstname + ", lastname=" + this.lastname + ", email=" + this.email + ")";
  36. }
  37. }
  38. }

3.9 @SneakyThrows

@SneakyThrows 注解用于自动抛出已检查的异常,而无需在方法中使用 throw 语句显式抛出。@SneakyThrows 注解的定义如下:

  1. @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface SneakyThrows {
  4. // 设置你希望向上抛的异常类
  5. Class<? extends Throwable>[] value() default java.lang.Throwable.class;
  6. }

示例

  1. public class SneakyThrowsDemo {
  2. @SneakyThrows
  3. @Override
  4. protected Object clone() {
  5. return super.clone();
  6. }
  7. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class SneakyThrowsDemo {
  2. public SneakyThrowsDemo() {
  3. }
  4. protected Object clone() {
  5. try {
  6. return super.clone();
  7. } catch (Throwable var2) {
  8. throw var2;
  9. }
  10. }
  11. }

3.10 @NonNull

可以在方法或构造函数的参数上使用 @NonNull 注解,它将会自动生成非空校验语句。@NonNull 注解的定义如下:

  1. @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
  2. @Retention(RetentionPolicy.CLASS)
  3. @Documented
  4. public @interface NonNull {
  5. }

示例

  1. public class NonNullDemo {
  2. @Getter
  3. @Setter
  4. @NonNull
  5. private String name;
  6. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class NonNullDemo {
  2. @NonNull
  3. private String name;
  4. public NonNullDemo() {
  5. }
  6. @NonNull
  7. public String getName() {
  8. return this.name;
  9. }
  10. public void setName(@NonNull String name) {
  11. if (name == null) {
  12. throw new NullPointerException("name is marked non-null but is null");
  13. } else {
  14. this.name = name;
  15. }
  16. }
  17. }

3.11 @Clean

@Clean 注解用于自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成 try-finally 这样的代码来关闭流。

  1. @Target(ElementType.LOCAL_VARIABLE)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Cleanup {
  4. // 设置用于执行资源清理/回收的方法名称,对应方法不能包含任何参数,默认名称为close。
  5. String value() default "close";
  6. }

示例

  1. public class CleanupDemo {
  2. public static void main(String[] args) throws IOException {
  3. @Cleanup InputStream in = new FileInputStream(args[0]);
  4. @Cleanup OutputStream out = new FileOutputStream(args[1]);
  5. byte[] b = new byte[10000];
  6. while (true) {
  7. int r = in.read(b);
  8. if (r == -1) break;
  9. out.write(b, 0, r);
  10. }
  11. }
  12. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class CleanupDemo {
  2. public CleanupDemo() {
  3. }
  4. public static void main(String[] args) throws IOException {
  5. FileInputStream in = new FileInputStream(args[0]);
  6. try {
  7. FileOutputStream out = new FileOutputStream(args[1]);
  8. try {
  9. byte[] b = new byte[10000];
  10. while(true) {
  11. int r = in.read(b);
  12. if (r == -1) {
  13. return;
  14. }
  15. out.write(b, 0, r);
  16. }
  17. } finally {
  18. if (Collections.singletonList(out).get(0) != null) {
  19. out.close();
  20. }
  21. }
  22. } finally {
  23. if (Collections.singletonList(in).get(0) != null) {
  24. in.close();
  25. }
  26. }
  27. }
  28. }

3.11 @With

在类的字段上应用 @With 注解之后,将会自动生成一个 withFieldName(newValue) 的方法,该方法会基于 newValue 调用相应构造函数,创建一个当前类对应的实例。@With 注解的定义如下:

  1. @Target({ElementType.FIELD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface With {
  4. AccessLevel value() default AccessLevel.PUBLIC;
  5. With.AnyAnnotation[] onMethod() default {};
  6. With.AnyAnnotation[] onParam() default {};
  7. @Deprecated
  8. @Retention(RetentionPolicy.SOURCE)
  9. @Target({})
  10. public @interface AnyAnnotation {
  11. }
  12. }

示例

  1. public class WithDemo {
  2. @With(AccessLevel.PROTECTED)
  3. @NonNull
  4. private final String name;
  5. @With
  6. private final int age;
  7. public WithDemo(String name, int age) {
  8. if (name == null) throw new NullPointerException();
  9. this.name = name;
  10. this.age = age;
  11. }
  12. }

以上代码经过 Lombok 编译后,会生成如下代码:

  1. public class WithDemo {
  2. @NonNull
  3. private final String name;
  4. private final int age;
  5. public WithDemo(String name, int age) {
  6. if (name == null) {
  7. throw new NullPointerException();
  8. } else {
  9. this.name = name;
  10. this.age = age;
  11. }
  12. }
  13. protected WithDemo withName(@NonNull String name) {
  14. if (name == null) {
  15. throw new NullPointerException("name is marked non-null but is null");
  16. } else {
  17. return this.name == name ? this : new WithDemo(name, this.age);
  18. }
  19. }
  20. public WithDemo withAge(int age) {
  21. return this.age == age ? this : new WithDemo(this.name, age);
  22. }
  23. }

3.12 其它特性

val

val 用在局部变量前面,相当于将变量声明为 final,此外 Lombok 在编译时还会自动进行类型推断。val 的使用示例:

  1. public class ValExample {
  2. public String example() {
  3. val example = new ArrayList<String>();
  4. example.add("Hello, World!");
  5. val foo = example.get(0);
  6. return foo.toLowerCase();
  7. }
  8. public void example2() {
  9. val map = new HashMap<Integer, String>();
  10. map.put(0, "zero");
  11. map.put(5, "five");
  12. for (val entry : map.entrySet()) {
  13. System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
  14. }
  15. }
  16. }

以上代码等价于:

  1. public class ValExample {
  2. public String example() {
  3. final ArrayList<String> example = new ArrayList<String>();
  4. example.add("Hello, World!");
  5. final String foo = example.get(0);
  6. return foo.toLowerCase();
  7. }
  8. public void example2() {
  9. final HashMap<Integer, String> map = new HashMap<Integer, String>();
  10. map.put(0, "zero");
  11. map.put(5, "five");
  12. for (final Map.Entry<Integer, String> entry : map.entrySet()) {
  13. System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
  14. }
  15. }
  16. }