平时定义类时,难免会写很多Getter, SettertoString, Constructor等方法。虽然可以用IDE自带的代码生成,但是生成的代码仍然很多,看起来特别臃肿。有了Lombok这个库,用一个注解就能自动搞定这个问题。

使用效果

没有对比就没有伤害。通过定义一个类,让我们来感受下Lombok的带来的便利。

不使用Lombok定义一个类PersonWithoutLombok.java, 虽然大部分代码都是IDE自动生成的,但是看起来仍然特别臃肿。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class PersonWithoutLombok {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "PersonWithoutLombok{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public PersonWithoutLombok() {
    }
}

使用Lombok之后,让我们来看看PersonWithLombok.java

1
2
3
4
5
6
7
import lombok.Data;

@Data
public class PersonWithLombok {
    private String name;
    private int age;
}

看看类结构

看看类结构

一样的效果,使用Lombok之后,整个代码看起来是不是更加清爽了呢?

除了Data之外。Lombok还提供了很多其它很多实用的注解,可以参考官方文档,每个注解的使用都配有使用示例,以及不使用注解的情况下,原始的Java代码该如何写,一对比非常容易理解。

安装配置

Lombok的使用也非常方便,可以直接在命令行Eclipse, IntelliJ中使用。也方便和Maven, Gradle集成,Android开发中同样适用。具体支持如下:

Setup

下面主要介绍下在命令行中和IntelliJ中的使用方式,其它的可以直接参考官方文档,都有非常详细的介绍

命令行中使用

  1. 下载最新版本的lombock.jar
  2. 创建PersonWithLombok.java类文件

    1
    
    $ cat PersonWithLombok.java
    1
    2
    3
    4
    5
    6
    7
    8
    
    import lombok.Data;
    
    
    @Data
    public class PersonWithLombok {
        private String name;
        private int age;
    }
  3. 编译PersonWithLombok.java类文件

    1
    
    $ javac -cp /path/to/lombok.jar PersonWithLombok.java
  4. 查看生成的class文件

    1
    
    $ javap PersonWithLombok.class
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    Compiled from "PersonWithLombok.java"
    public class PersonWithLombok {
      public PersonWithLombok();
      public java.lang.String getName();
      public int getAge();
      public void setName(java.lang.String);
      public void setAge(int);
      public boolean equals(java.lang.Object);
      protected boolean canEqual(java.lang.Object);
      public int hashCode();
      public java.lang.String toString();
    }

    可以看到自动生成了相关代码

IntelliJ中使用

  1. 安装插件

    Preferences > Settings > Plugins > Browse repositories... > Search for "lombok" > Install Plugin

    然后重启IDE

    安装插件

  2. 配置IDE的编译器,开启

    Preferences -> Build, Execution, Deployment -> Compiler, Annotation Processors. 点击Enable Annotation Processing,并勾选Obtain processors from project classpath

    配置IDE,启用Annotation Processing

  3. 添加Lombok到项目依赖。这里根据使用的构建工具不同,操作也不同。

    • 如果使用的是Gradle, 在build.gradle中添加如下内容

      1
      2
      3
      
      // 'compile' can be changed to 'compileOnly' for Gradle 2.12+
      // or 'provided' if using 'propdeps' plugin from SpringSource
      compile "org.projectlombok:lombok:1.18.8"
    • 如果使用的是Maven,直接在pom.xml中添加如下内容

      1
      2
      3
      4
      5
      6
      7
      8
      
      <dependencies>
          <dependency>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
              <version>1.18.8</version>
              <scope>provided</scope>
          </dependency>
      </dependencies>
    • 如果使用的是Ivy, 在ivy.xml中添加如下内容

      1
      
      <dependency org="org.projectlombok" name="lombok" rev="1.18.8" conf="build" />
    • 如果没有使用任何构建工具,那需要手动下载lombock.jar, 然后在项目结构中,把下载的lombok.jar添加到项目依赖的Libraries

      添加lombok.jar到项目的classpath中

  4. 创建一个类PersonWithLombok.java,测试效果,如下图,从类结构中可以看到,IDE已经自动识别出使用Lombok后生成的代码

    效果图

常用注解介绍

val

作用在局部变量,用于定义一个局部变量,并将它声明为final, 不用声明变量类型,它会根据初始赋值自动推动变量类型。只能用于局部变量或loop循环中,不能用于类的属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.ArrayList;
import java.util.HashMap;
import lombok.val;

public class ValExample {
  public String example() {
    val example = new ArrayList<String>();
    example.add("Hello, World!");
    val foo = example.get(0);
    return foo.toLowerCase();
  }

  public void example2() {
    val map = new HashMap<Integer, String>();
    map.put(0, "zero");
    map.put(5, "five");
    for (val entry : map.entrySet()) {
      System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
    }
  }
}

等效于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ValExample {
  public String example() {
    final ArrayList<String> example = new ArrayList<String>();
    example.add("Hello, World!");
    final String foo = example.get(0);
    return foo.toLowerCase();
  }

  public void example2() {
    final HashMap<Integer, String> map = new HashMap<Integer, String>();
    map.put(0, "zero");
    map.put(5, "five");
    for (final Map.Entry<Integer, String> entry : map.entrySet()) {
      System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
    }
  }
}

var

val功能类似,除了变量不会标记为final

@NonNull

非空检查

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;

  public NonNullExample(@NonNull Person person) {
    super("Hello");
    this.name = person.getName();
  }
}

等效于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;

  public NonNullExample(@NonNull Person person) {
    super("Hello");
    if (person == null) {
      throw new NullPointerException("person is marked @NonNull but is null");
    }
    this.name = person.getName();
  }
}

@Cleanup

资源管理,自动调用close()方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import lombok.Cleanup;
import java.io.*;

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

等价于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.io.*;

public class CleanupExample {
  public static void main(String[] args) throws IOException {
    InputStream in = new FileInputStream(args[0]);
    try {
      OutputStream out = new FileOutputStream(args[1]);
      try {
        byte[] b = new byte[10000];
        while (true) {
          int r = in.read(b);
          if (r == -1) break;
          out.write(b, 0, r);
        }
      } finally {
        if (out != null) {
          out.close();
        }
      }
    } finally {
      if (in != null) {
        in.close();
      }
    }
  }
}

@Getter @Setter

自动生成GetterSetter代码

  • 默认情况下,生成的getter/setter方法被标记为public,除非指定了AccessLevel

  • 同样可以加@Getter@Setter注解作用到类上, 那样类中所有的非静态属性都会自动生成getter/setter代码

  • 如果不想给某个属性自动生成getter/setter代码,可以标记类属性为AccessLevel.NONE。这样可以覆盖给类添加@Getter, @Setter @Data产生的行为。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    import lombok.AccessLevel;
    import lombok.Getter;
    import lombok.Setter;
    
    public class GetterSetterExample {
    /**
    * 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;
    
    /**
    * Name of the person.
    * -- SETTER --
    * Changes the name of this person.
    *
    * @param name The new value.
    */
    @Setter(AccessLevel.PROTECTED) private String name;
    
    @Override public String toString() {
    return String.format("%s (age: %d)", name, age);
    }
    }

等价于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class GetterSetterExample {
  /**
   * Age of the person. Water is wet.
   */
  private int age = 10;

  /**
   * Name of the person.
   */
  private String name;

  @Override public String toString() {
    return String.format("%s (age: %d)", name, age);
  }

  /**
   * 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;
  }

  /**
   * Changes the name of this person.
   *
   * @param name The new value.
   */
  protected void setName(String name) {
    this.name = name;
  }
}

@ToString

自动添加toSting()方法,默认使用类名 + 所有的非静态属性值。

可以通过@ToString.Exclude来排除一些不想添加到toString()中的属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import lombok.ToString;

@ToString
public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  @ToString.Exclude private int id;

  public String getName() {
    return this.name;
  }

  @ToString(callSuper=true, includeFieldNames=true)
  public static class Square extends Shape {
    private final int width, height;

    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
  }
}

等价于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Arrays;

public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;

  public String getName() {
    return this.getName();
  }

  public static class Square extends Shape {
    private final int width, height;

    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }

    @Override public String toString() {
      return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
    }
  }

  @Override public String toString() {
    return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  }
}

@Data

相当于@ToString, @EqualsAndHashCode, @Getter,@Setter,@RequiredArgsConstructor的组合

@Log

自动为类添加log属性,方便直接使用log

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

@Log
public class LogExample {

  public static void main(String... args) {
    log.severe("Something's wrong here");
  }
}

@Slf4j
public class LogExampleOther {

  public static void main(String... args) {
    log.error("Something else is wrong here");
  }
}

@CommonsLog(topic="CounterLog")
public class LogExampleCategory {

  public static void main(String... args) {
    log.error("Calling the 'CounterLog' with a message");
  }
}

等价于

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class LogExample {
  private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

  public static void main(String... args) {
    log.severe("Something's wrong here");
  }
}

public class LogExampleOther {
  private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);

  public static void main(String... args) {
    log.error("Something else is wrong here");
  }
}

public class LogExampleCategory {
  private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");

  public static void main(String... args) {
    log.error("Calling the 'CounterLog' with a message");
  }
}

下面注解的使用,可以参考官方文档

@Value

@Builder

@Synchronized

@SneakyThrows

@With

@EqualsAndHashCode

@NoArgsConstructor @RequiredArgsConstructor @AllArgsConstructor

@Getter(lazy=true)

赶紧拿起你的电脑试试吧!