文章来源公众号:猿人谷

官方介绍如下:

  1. Project Lombok makes java a spicier language by adding 'handlers' that know how to build and compile simple, boilerplate-free, not-quite-java code.

大致意思是Lombok通过增加一些“处理程序”,可以让java变得简洁、快速。

Lombok能以简单的注解形式来简化java代码,提高开发人员的开发效率。例如开发中经常需要写的javabean,都需要花时间去添加相应的getter/setter,也许还要去写构造器、equals等方法,而且需要维护,当属性多时会出现大量的getter/setter方法,这些显得很冗长也没有太多技术含量,一旦修改属性,就容易出现忘记修改对应方法的失误。

Lombok能通过注解的方式,在编译时自动为属性生成构造器、getter/setter、equals、hashcode、toString方法。出现的神奇就是在源码中没有getter和setter方法,但是在编译生成的字节码文件中有getter和setter方法。这样就省去了手动重建这些代码的麻烦,使代码看起来更简洁些。

Lombok的使用跟引用jar包一样,可以在官网(https://projectlombok.org/download)下载jar包,也可以使用maven添加依赖:

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

接下来我们来分析Lombok中注解的具体用法。

@Data注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。

官方实例如下:

  1. import lombok.AccessLevel;
  2. import lombok.Setter;
  3. import lombok.Data;
  4. import lombok.ToString;
  5. @Data public class DataExample {
  6. private final String name;
  7. @Setter(AccessLevel.PACKAGE) private int age;
  8. private double score;
  9. private String[] tags;
  10. @ToString(includeFieldNames=true)
  11. @Data(staticConstructor="of")
  12. public static class Exercise<T> {
  13. private final String name;
  14. private final T value;
  15. }
  16. }

如不使用Lombok,则实现如下:

  1. import java.util.Arrays;
  2. public class DataExample {
  3. private final String name;
  4. private int age;
  5. private double score;
  6. private String[] tags;
  7. public DataExample(String name) {
  8. this.name = name;
  9. }
  10. public String getName() {
  11. return this.name;
  12. }
  13. void setAge(int age) {
  14. this.age = age;
  15. }
  16. public int getAge() {
  17. return this.age;
  18. }
  19. public void setScore(double score) {
  20. this.score = score;
  21. }
  22. public double getScore() {
  23. return this.score;
  24. }
  25. public String[] getTags() {
  26. return this.tags;
  27. }
  28. public void setTags(String[] tags) {
  29. this.tags = tags;
  30. }
  31. @Override public String toString() {
  32. return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
  33. }
  34. protected boolean canEqual(Object other) {
  35. return other instanceof DataExample;
  36. }
  37. @Override public boolean equals(Object o) {
  38. if (o == this) return true;
  39. if (!(o instanceof DataExample)) return false;
  40. DataExample other = (DataExample) o;
  41. if (!other.canEqual((Object)this)) return false;
  42. if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
  43. if (this.getAge() != other.getAge()) return false;
  44. if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
  45. if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
  46. return true;
  47. }
  48. @Override public int hashCode() {
  49. final int PRIME = 59;
  50. int result = 1;
  51. final long temp1 = Double.doubleToLongBits(this.getScore());
  52. result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
  53. result = (result*PRIME) + this.getAge();
  54. result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
  55. result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
  56. return result;
  57. }
  58. public static class Exercise<T> {
  59. private final String name;
  60. private final T value;
  61. private Exercise(String name, T value) {
  62. this.name = name;
  63. this.value = value;
  64. }
  65. public static <T> Exercise<T> of(String name, T value) {
  66. return new Exercise<T>(name, value);
  67. }
  68. public String getName() {
  69. return this.name;
  70. }
  71. public T getValue() {
  72. return this.value;
  73. }
  74. @Override public String toString() {
  75. return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
  76. }
  77. protected boolean canEqual(Object other) {
  78. return other instanceof Exercise;
  79. }
  80. @Override public boolean equals(Object o) {
  81. if (o == this) return true;
  82. if (!(o instanceof Exercise)) return false;
  83. Exercise<?> other = (Exercise<?>) o;
  84. if (!other.canEqual((Object)this)) return false;
  85. if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
  86. if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
  87. return true;
  88. }
  89. @Override public int hashCode() {
  90. final int PRIME = 59;
  91. int result = 1;
  92. result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
  93. result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
  94. return result;
  95. }
  96. }
  97. }

如果觉得@Data太过残暴(因为@Data集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性)不够精细,可以使用@Getter/@Setter注解,此注解在属性上,可以为相应的属性自动生成Getter/Setter方法,示例如下:

  1. import lombok.AccessLevel;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. public class GetterSetterExample {
  5. @Getter @Setter private int age = 10;
  6. @Setter(AccessLevel.PROTECTED) private String name;
  7. @Override public String toString() {
  8. return String.format("%s (age: %d)", name, age);
  9. }
  10. }

如果不使用Lombok:

  1. public class GetterSetterExample {
  2. private int age = 10;
  3. private String name;
  4. @Override public String toString() {
  5. return String.format("%s (age: %d)", name, age);
  6. }
  7. public int getAge() {
  8. return age;
  9. }
  10. public void setAge(int age) {
  11. this.age = age;
  12. }
  13. protected void setName(String name) {
  14. this.name = name;
  15. }
  16. }

该注解用在属性或构造器上,Lombok会生成一个非空的声明,可用于校验参数,能帮助避免空指针。

示例如下:

  1. import lombok.NonNull;
  2. public class NonNullExample extends Something {
  3. private String name;
  4. public NonNullExample(@NonNull Person person) {
  5. super("Hello");
  6. this.name = person.getName();
  7. }
  8. }

不使用Lombok:

  1. import lombok.NonNull;
  2. public class NonNullExample extends Something {
  3. private String name;
  4. public NonNullExample(@NonNull Person person) {
  5. super("Hello");
  6. if (person == null) {
  7. throw new NullPointerException("person");
  8. }
  9. this.name = person.getName();
  10. }
  11. }

该注解能帮助我们自动调用close()方法,很大的简化了代码。

示例如下:

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

如不使用Lombok,则需如下:

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

默认情况下,会使用所有非静态(non-static)和非瞬态(non-transient)属性来生成equals和hasCode,也能通过exclude注解来排除一些属性。

示例如下:

  1. import lombok.EqualsAndHashCode;
  2. @EqualsAndHashCode(exclude={"id", "shape"})
  3. public class EqualsAndHashCodeExample {
  4. private transient int transientVar = 10;
  5. private String name;
  6. private double score;
  7. private Shape shape = new Square(5, 10);
  8. private String[] tags;
  9. private int id;
  10. public String getName() {
  11. return this.name;
  12. }
  13. @EqualsAndHashCode(callSuper=true)
  14. public static class Square extends Shape {
  15. private final int width, height;
  16. public Square(int width, int height) {
  17. this.width = width;
  18. this.height = height;
  19. }
  20. }
  21. }

类使用@ToString注解,Lombok会生成一个toString()方法,默认情况下,会输出类名、所有属性(会按照属性定义顺序),用逗号来分割。

通过将includeFieldNames参数设为true,就能明确的输出toString()属性。这一点是不是有点绕口,通过代码来看会更清晰些。

使用Lombok的示例:

  1. import lombok.ToString;
  2. @ToString(exclude="id")
  3. public class ToStringExample {
  4. private static final int STATIC_VAR = 10;
  5. private String name;
  6. private Shape shape = new Square(5, 10);
  7. private String[] tags;
  8. private int id;
  9. public String getName() {
  10. return this.getName();
  11. }
  12. @ToString(callSuper=true, includeFieldNames=true)
  13. public static class Square extends Shape {
  14. private final int width, height;
  15. public Square(int width, int height) {
  16. this.width = width;
  17. this.height = height;
  18. }
  19. }
  20. }

不使用Lombok的示例如下:

  1. import java.util.Arrays;
  2. public class ToStringExample {
  3. private static final int STATIC_VAR = 10;
  4. private String name;
  5. private Shape shape = new Square(5, 10);
  6. private String[] tags;
  7. private int id;
  8. public String getName() {
  9. return this.getName();
  10. }
  11. public static class Square extends Shape {
  12. private final int width, height;
  13. public Square(int width, int height) {
  14. this.width = width;
  15. this.height = height;
  16. }
  17. @Override public String toString() {
  18. return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
  19. }
  20. }
  21. @Override public String toString() {
  22. return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  23. }
  24. }

无参构造器、部分参数构造器、全参构造器。Lombok没法实现多种参数构造器的重载。

Lombok示例代码如下:

  1. import lombok.AccessLevel;
  2. import lombok.RequiredArgsConstructor;
  3. import lombok.AllArgsConstructor;
  4. import lombok.NonNull;
  5. @RequiredArgsConstructor(staticName = "of")
  6. @AllArgsConstructor(access = AccessLevel.PROTECTED)
  7. public class ConstructorExample<T> {
  8. private int x, y;
  9. @NonNull private T description;
  10. @NoArgsConstructor
  11. public static class NoArgsExample {
  12. @NonNull private String field;
  13. }
  14. }

不使用Lombok的示例如下:

  1. public class ConstructorExample<T> {
  2. private int x, y;
  3. @NonNull private T description;
  4. private ConstructorExample(T description) {
  5. if (description == null) throw new NullPointerException("description");
  6. this.description = description;
  7. }
  8. public static <T> ConstructorExample<T> of(T description) {
  9. return new ConstructorExample<T>(description);
  10. }
  11. @java.beans.ConstructorProperties({"x", "y", "description"})
  12. protected ConstructorExample(int x, int y, T description) {
  13. if (description == null) throw new NullPointerException("description");
  14. this.x = x;
  15. this.y = y;
  16. this.description = description;
  17. }
  18. public static class NoArgsExample {
  19. @NonNull private String field;
  20. public NoArgsExample() {
  21. }
  22. }
  23. }

会发现在Lombok使用的过程中,只需要添加相应的注解,无需再为此写任何代码。自动生成的代码到底是如何产生的呢?

核心之处就是对于注解的解析上。JDK5引入了注解的同时,也提供了两种解析方式。

  • 运行时解析

运行时能够解析的注解,必须将@Retention设置为RUNTIME,这样就可以通过反射拿到该注解。java.lang,reflect反射包中提供了一个接口AnnotatedElement,该接口定义了获取注解信息的几个方法,Class、Constructor、Field、Method、Package等都实现了该接口,对反射熟悉的朋友应该都会很熟悉这种解析方式。

  • 编译时解析

编译时解析有两种机制,分别简单描述下:

1)Annotation Processing Tool

apt自JDK5产生,JDK7已标记为过期,不推荐使用,JDK8中已彻底删除,自JDK6开始,可以使用Pluggable Annotation Processing API来替换它,apt被替换主要有2点原因:

  • api都在com.sun.mirror非标准包下
  • 没有集成到javac中,需要额外运行

2)Pluggable Annotation Processing API

JSR 269自JDK6加入,作为apt的替代方案,它解决了apt的两个问题,javac在执行的时候会调用实现了该API的程序,这样我们就可以对编译器做一些增强,这时javac执行的过程如下:

123

Lombok本质上就是一个实现了“JSR 269 API”的程序。在使用javac的过程中,它产生作用的具体流程如下:

  1. javac对源代码进行分析,生成了一棵抽象语法树(AST)
  2. 运行过程中调用实现了“JSR 269 API”的Lombok程序
  3. 此时Lombok就对第一步骤得到的AST进行处理,找到@Data注解所在类对应的语法树(AST),然后修改该语法树(AST),增加getter和setter方法定义的相应树节点
  4. javac使用修改后的抽象语法树(AST)生成字节码文件,即给class增加新的节点(代码块)

拜读了Lombok源码,对应注解的实现都在HandleXXX中,比如@Getter注解的实现时HandleGetter.handle()。还有一些其它类库使用这种方式实现,比如Google AutoDagger等等。

优点:

  1. 能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
  2. 让代码变得简洁,不用过多的去关注相应的方法
  3. 属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等

缺点:

  1. 不支持多种参数构造器的重载
  2. 虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度

Lombok虽然有很多优点,但Lombok更类似于一种IDE插件,项目也需要依赖相应的jar包。Lombok依赖jar包是因为编译时要用它的注解,为什么说它又类似插件?因为在使用时,eclipse或IntelliJ IDEA都需要安装相应的插件,在编译器编译时通过操作AST(抽象语法树)改变字节码生成,变向的就是说它在改变java语法。它不像spring的依赖注入或者mybatis的ORM一样是运行时的特性,而是编译时的特性。这里我个人最感觉不爽的地方就是对插件的依赖!因为Lombok只是省去了一些人工生成代码的麻烦,但IDE都有快捷键来协助生成getter/setter等方法,也非常方便。

知乎上有位大神发表过对Lombok的一些看法:

  1. 这是一种低级趣味的插件,不建议使用。JAVA发展到今天,各种插件层出不穷,如何甄别各种插件的优劣?能从架构上优化你的设计的,能提高应用程序性能的
  2. 实现高度封装可扩展的..., lombok这种,像这种插件,已经不仅仅是插件了,改变了你如何编写源码,事实上,少去了代码你写上去又如何?
  3. 如果JAVA家族到处充斥这样的东西,那只不过是一坨披着金属颜色的屎,迟早会被其它的语言取代。

虽然话糙但理确实不糙,试想一个项目有非常多类似Lombok这样的插件,个人觉得真的会极大的降低阅读源代码的舒适度。

虽然非常不建议在属性的getter/setter写一些业务代码,但在多年项目的实战中,有时通过给getter/setter加一点点业务代码,能极大的简化某些业务场景的代码。所谓取舍,也许就是这时的舍弃一定的规范,取得极大的方便。

我现在非常坚信一条理念,任何编程语言或插件,都仅仅只是工具而已,即使工具再强大也在于用的人,就如同小米加步枪照样能赢飞机大炮的道理一样。结合具体业务场景和项目实际情况,无需一味追求高大上的技术,适合的才是王道。

Lombok有它的得天独厚的优点,也有它避之不及的缺点,熟知其优缺点,在实战中灵活运用才是王道。

参考:

https://projectlombok.org/features/

https://github.com/rzwitserloot/lombok?spm=a2c4e.11153940.blogcont59972.5.2aeb6d32hayLHv

https://www.zhihu.com/question/42348457

https://blog.csdn.net/ghsau/article/details/52334762

版权声明:本文为alterem原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/alterem/p/11611417.html