Java实用第三方库之Lombok使用入门

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

使用效果

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

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

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

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类文件

    $ cat PersonWithLombok.java
    
    import lombok.Data;
    
    
    @Data
    public class PersonWithLombok {
        private String name;
        private int age;
    }
    
  3. 编译PersonWithLombok.java类文件

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

    $ javap PersonWithLombok.class
    
    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
  1. 添加Lombok到项目依赖。这里根据使用的构建工具不同,操作也不同。

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

      // '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中添加如下内容

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

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

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

    效果图

常用注解介绍

val

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

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());
    }
  }
}

等效于

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

非空检查

import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;

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

等效于


 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()方法

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);
    }
  }
}

等价于

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产生的行为。

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);
  }
}

等价于

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()中的属性

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

等价于

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

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");
  }
}

等价于

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)

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容