一、Lombok 简介

Lombok 是一款 Java 开发插件,使得 Java 开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的 Java 模型对象(POJO)。

在开发环境中使用 Lombok 插件后,Java 开发人员可以节省出重复构建,诸如 hashCode 和 equals 这样的方法以及各种业务对象模型的 accessor 和 toString 等方法的大量时间。对于这些方法,Lombok 能够在编译源代码期间自动帮我们生成这些方法,但并不会像反射那样降低程序的性能。

打开网易新闻 查看更多图片

二、Lombok 安装

2.1 构建工具

  • Gradle

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

dependencies {
compileOnly 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'org.projectlombok:lombok:1.18.10'
}

  • Maven

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

org.projectlombokgroupId>
lombokartifactId>
1.18.10version>
providedscope>
dependency>

  • Ant

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

javac>

2.2 IDE

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

三、Lombok 详解

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

3.1 @Getter and @Setter

你可以使用 或 注释任何类或字段,Lombok 会自动生成默认的 方法。

@Getter

@Setter

getter/setter

  • @Getter 注解

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

  • @Setter

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

使用示例

@Getter
@Setter
publicclass GetterAndSetterDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
}

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

publicclass GetterAndSetterDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
public GetterAndSetterDemo() {
}
// 省略其它setter和getter方法
public String getFirstName() {
returnthis.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

  • Lazy Getter

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

示例

publicclass LazyGetterDemo {
public static void main(String[] args) {
LazyGetterDemo m = new LazyGetterDemo();
System.out.println("Main instance is created");
m.getLazy();
}
@Getter
privatefinal String notLazy = createValue("not lazy");
@Getter(lazy = true)
privatefinal String lazy = createValue("lazy");
private String createValue(String name) {
System.out.println("createValue(" + name + ")");
returnnull;
}
}

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

publicclass LazyGetterDemo {
privatefinal String notLazy = this.createValue("not lazy");
privatefinal AtomicReference lazy = new AtomicReference();
// 已省略部分代码
public String getNotLazy() {
returnthis.notLazy;
}
public String getLazy() {
Object value = this.lazy.get();
if (value == null) {
synchronized(this.lazy) {
value = this.lazy.get();
if (value == null) {
String actualValue = this.createValue("lazy");
value = actualValue == null ? this.lazy : actualValue;
this.lazy.set(value);
}
}
}
return (String)((String)(value == this.lazy ? null : value));
}
}

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

3.2 Constructor Annotations

  • @NoArgsConstructor

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

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

示例

@NoArgsConstructor(staticName = "getInstance")
publicclass NoArgsConstructorDemo {
privatelong id;
private String name;
privateint age;
}

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

publicclass NoArgsConstructorDemo {
privatelong id;
private String name;
privateint age;
private NoArgsConstructorDemo() {
}
public static NoArgsConstructorDemo getInstance() {
returnnew NoArgsConstructorDemo();
}
}

  • @AllArgsConstructor

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

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

示例

@AllArgsConstructor
publicclass AllArgsConstructorDemo {
privatelong id;
private String name;
privateint age;
}

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

publicclass AllArgsConstructorDemo {
privatelong id;
private String name;
privateint age;
public AllArgsConstructorDemo(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}

  • @RequiredArgsConstructor

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

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

示例

@RequiredArgsConstructor
publicclass RequiredArgsConstructorDemo {
privatefinallong id;
private String name;
privateint age;
}

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

publicclass RequiredArgsConstructorDemo {
privatefinallong id;
private String name;
privateint age;
public RequiredArgsConstructorDemo(long id) {
this.id = id;
}
}

3.3 @EqualsAndHashCode

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public@interface EqualsAndHashCode {
// 指定在生成的equals和hashCode方法中需要排除的字段列表
String[] exclude() default {};
// 显式列出用于identity的字段,一般情况下non-static,non-transient字段会被用于identity
String[] of() default {};
// 标识在执行字段计算前,是否调用父类的equals和hashCode方法
boolean callSuper() default false;
boolean doNotUseGetters() default false;
AnyAnnotation[] onParam() default {};
@Deprecated
@Retention(RetentionPolicy.SOURCE)
@Target({})
@interface AnyAnnotation {}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public@interface Exclude {}
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public@interface Include {
String replaces() default "";
}
}

示例

@EqualsAndHashCode
publicclass EqualsAndHashCodeDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
}

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

publicclass EqualsAndHashCodeDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
public EqualsAndHashCodeDemo() {
}
public boolean equals(Object o) {
if (o == this) {
returntrue;
} elseif (!(o instanceof EqualsAndHashCodeDemo)) {
returnfalse;
} else {
EqualsAndHashCodeDemo other = (EqualsAndHashCodeDemo)o;
if (!other.canEqual(this)) {
returnfalse;
} else {
// 已省略大量代码
}
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $firstName = this.firstName;
int result = result * 59 + ($firstName == null ? 43 : $firstName.hashCode());
Object $lastName = this.lastName;
result = result * 59 + ($lastName == null ? 43 : $lastName.hashCode());
Object $dateOfBirth = this.dateOfBirth;
result = result * 59 + ($dateOfBirth == null ? 43 : $dateOfBirth.hashCode());
return result;
}
}

3.4 @ToString

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public@interface ToString {
// 打印输出时是否包含字段的名称
boolean includeFieldNames() default true;
// 列出打印输出时,需要排除的字段列表
String[] exclude() default {};
// 显式的列出需要打印输出的字段列表
String[] of() default {};
// 打印输出的结果中是否包含父类的toString方法的返回结果
boolean callSuper() default false;
boolean doNotUseGetters() default false;
boolean onlyExplicitlyIncluded() default false;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public@interface Exclude {}
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public@interface Include {
int rank() default 0;
String name() default "";
}
}

示例

@ToString(exclude = {"dateOfBirth"})
publicclass ToStringDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
}

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

publicclass ToStringDemo {
String firstName;
String lastName;
LocalDate dateOfBirth;
public ToStringDemo() {
}
public String toString() {
return"ToStringDemo(firstName=" + this.firstName + ", lastName=" +
this.lastName + ")";
}
}

3.5 @Data

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

@ToString
@Getter
@Setter
@RequiredArgsConstructor
@EqualsAndHashCode

@Data 注解的定义如下:

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

示例

@Data
publicclass DataDemo {
private Long id;
private String summary;
private String description;
}

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

publicclass DataDemo {
private Long id;
private String summary;
private String description;
public DataDemo() {
}
// 省略summary和description成员属性的setter和getter方法
public Long getId() {
returnthis.id;
}
public void setId(Long id) {
this.id = id;
}
public boolean equals(Object o) {
if (o == this) {
returntrue;
} elseif (!(o instanceof DataDemo)) {
returnfalse;
} else {
DataDemo other = (DataDemo)o;
if (!other.canEqual(this)) {
returnfalse;
} else {
// 已省略大量代码
}
}
}
protected boolean canEqual(Object other) {
return other instanceof DataDemo;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $id = this.getId();
int result = result * 59 + ($id == null ? 43 : $id.hashCode());
Object $summary = this.getSummary();
result = result * 59 + ($summary == null ? 43 : $summary.hashCode());
Object $description = this.getDescription();
result = result * 59 + ($description == null ? 43 : $description.hashCode());
return result;
}
public String toString() {
return"DataDemo(id=" + this.getId() + ", summary=" + this.getSummary() + ", description=" + this.getDescription() + ")";
}
}

3.6 @Log

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

@Log
privatestaticfinal java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
@Log4j
privatestaticfinal org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);
@Log4j2
privatestaticfinal org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
@Slf4j
privatestaticfinal org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
@XSlf4j
privatestaticfinal org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
@CommonsLog
privatestaticfinal 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 注解的定义如下:

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

示例

publicclass SynchronizedDemo {
privatefinal Object readLock = new Object();
@Synchronized
public static void hello() {
System.out.println("world");
}
@Synchronized
public int answerToLife() {
return42;
}
@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
}

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

publicclass SynchronizedDemo {
privatestaticfinal Object $LOCK = new Object[0];
privatefinal Object $lock = new Object[0];
privatefinal Object readLock = new Object();
public SynchronizedDemo() {
}
public static void hello() {
synchronized($LOCK) {
System.out.println("world");
}
}
public int answerToLife() {
synchronized(this.$lock) {
return42;
}
}
public void foo() {
synchronized(this.readLock) {
System.out.println("bar");
}
}
}

3.8 @Builder

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

@Target({TYPE, METHOD, CONSTRUCTOR})
@Retention(SOURCE)
public@interface Builder {
@Target(FIELD)
@Retention(SOURCE)
public@interface Default {}
// 创建新的builder实例的方法名称
String builderMethodName() default "builder";
// 创建Builder注解类对应实例的方法名称
String buildMethodName() default "build";
// builder类的名称
String builderClassName() default "";
boolean toBuilder() default false;
AccessLevel access() default lombok.AccessLevel.PUBLIC;
@Target({FIELD, PARAMETER})
@Retention(SOURCE)
public@interface ObtainVia {
String field() default "";
String method() default "";
boolean isStatic() default false;
}
}

示例

@Builder
publicclass BuilderDemo {
privatefinal String firstname;
privatefinal String lastname;
privatefinal String email;
}

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

publicclass BuilderDemo {
privatefinal String firstname;
privatefinal String lastname;
privatefinal String email;
BuilderDemo(String firstname, String lastname, String email) {
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}
publicstatic BuilderDemo.BuilderDemoBuilder builder() {
returnnew BuilderDemo.BuilderDemoBuilder();
}
publicstaticclass BuilderDemoBuilder {
private String firstname;
private String lastname;
private String email;
BuilderDemoBuilder() {
}
public BuilderDemo.BuilderDemoBuilder firstname(String firstname) {
this.firstname = firstname;
returnthis;
}
public BuilderDemo.BuilderDemoBuilder lastname(String lastname) {
this.lastname = lastname;
returnthis;
}
public BuilderDemo.BuilderDemoBuilder email(String email) {
this.email = email;
returnthis;
}
public BuilderDemo build() {
returnnew BuilderDemo(this.firstname, this.lastname, this.email);
}
public String toString() {
return"BuilderDemo.BuilderDemoBuilder(firstname=" + this.firstname + ", lastname=" + this.lastname + ", email=" + this.email + ")";
}
}
}

3.9 @SneakyThrows

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

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

示例

publicclass SneakyThrowsDemo {
@SneakyThrows
@Override
protected Object clone() {
returnsuper.clone();
}
}

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

publicclass SneakyThrowsDemo {
public SneakyThrowsDemo() {
}
protected Object clone() {
try {
returnsuper.clone();
} catch (Throwable var2) {
throw var2;
}
}
}

3.10 @NonNull

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

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

示例

publicclass NonNullDemo {
@Getter
@Setter
@NonNull
private String name;
}

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

publicclass NonNullDemo {
@NonNull
private String name;
public NonNullDemo() {
}
@NonNull
public String getName() {
returnthis.name;
}
public void setName(@NonNull String name) {
if (name == null) {
thrownew NullPointerException("name is marked non-null but is null");
} else {
this.name = name;
}
}
}

3.11 @Clean

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

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

示例

publicclass CleanupDemo {
public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] b = newbyte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
}
}

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

publicclass CleanupDemo {
public CleanupDemo() {
}
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream(args[0]);
try {
FileOutputStream out = new FileOutputStream(args[1]);
try {
byte[] b = newbyte[10000];
while(true) {
int r = in.read(b);
if (r == -1) {
return;
}
out.write(b, 0, r);
}
} finally {
if (Collections.singletonList(out).get(0) != null) {
out.close();
}
}
} finally {
if (Collections.singletonList(in).get(0) != null) {
in.close();
}
}
}
}

3.11 @With

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

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public@interface With {
AccessLevel value() default AccessLevel.PUBLIC;
With.AnyAnnotation[] onMethod() default {};
With.AnyAnnotation[] onParam() default {};
@Deprecated
@Retention(RetentionPolicy.SOURCE)
@Target({})
public@interface AnyAnnotation {
}
}

示例

publicclass WithDemo {
@With(AccessLevel.PROTECTED)
@NonNull
privatefinal String name;
@With
privatefinalint age;
public WithDemo(String name, int age) {
if (name == null) thrownew NullPointerException();
this.name = name;
this.age = age;
}
}

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

publicclass WithDemo {
@NonNull
privatefinal String name;
privatefinalint age;
public WithDemo(String name, int age) {
if (name == null) {
thrownew NullPointerException();
} else {
this.name = name;
this.age = age;
}
}
protected WithDemo withName(@NonNull String name) {
if (name == null) {
thrownew NullPointerException("name is marked non-null but is null");
} else {
returnthis.name == name ? this : new WithDemo(name, this.age);
}
}
public WithDemo withAge(int age) {
returnthis.age == age ? this : new WithDemo(this.name, age);
}
}

3.12 其它特性

  • val

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

publicclass ValExample {
public String example() {
val example = new ArrayList

();
example.add("Hello, World!");
val foo = example.get(0);
return foo.toLowerCase();
}
public void example2() {
val map = new HashMap

();
map.put(0, "zero");
map.put(5, "five");
for (val entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
}
}

以上代码等价于:

publicclass ValExample {
public String example() {
final ArrayList

example = new ArrayList

();
example.add("Hello, World!");
final String foo = example.get(0);
return foo.toLowerCase();
}
public void example2() {
final HashMap

map = new HashMap

();
map.put(0, "zero");
map.put(5, "five");
for (final Map.Entry

entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
}
}

至此功能强大的 Lombok 工具就介绍完了。

本文地址:segmentfault.com/a/1190000020864572