Lombok 使用小结

Lombok 简介

Lombok 是一种 Java 实用工具,可用来帮助开发人员消除 Java 的冗长,尤其是对于简单的 Java 对象(POJO)。它通过注释实现这一目的。通过在开发环境中实现 Lombok,开发人员可以节省构建诸如 hashCode()equals()getter / setter 这样的方法以及以往用来分类各种 accessor 和 mutator 的大量时间。

Lombok 安装

使 IntelliJ IDEA 支持 Lombok 方式如下:

  • Intellij 设置支持注解处理

点击 File > Settings > Build > Annotation Processors

勾选 Enable annotation processing

  • 安装插件

点击 Settings > Plugins > Browse repositories

查找 Lombok Plugin 并进行安装

重启 IntelliJ IDEA

  • 将 lombok 添加到 pom 文件
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.8</version>
</dependency>

Lombok 使用

API

Lombok 提供注解API 来修饰指定的类:

@Getter and @Setter

@Getter and @Setter Lombok 代码:

@Getter @Setter private boolean employed = true;
@Setter(AccessLevel.PROTECTED) private String name;

等价于 Java 源码:

private boolean employed = true;
private String name;

public boolean isEmployed() {
    return employed;
}

public void setEmployed(final boolean employed) {
    this.employed = employed;
}

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

@NonNull

@NonNull Lombok 代码:

@Getter @Setter @NonNull
private List<Person> members;

等价于 Java 源码:

@NonNull
private List<Person> members;

public Family(@NonNull final List<Person> members) {
    if (members == null) throw new java.lang.NullPointerException("members");
    this.members = members;
}
    
@NonNull
public List<Person> getMembers() {
    return members;
}

public void setMembers(@NonNull final List<Person> members) {
    if (members == null) throw new java.lang.NullPointerException("members");
    this.members = members;
}

@ToString

@ToString Lombok 代码:

@ToString(callSuper=true,exclude="someExcludedField")
public class Foo extends Bar {
    private boolean someBoolean = true;
    private String someStringField;
    private float someExcludedField;
}

等价于 Java 源码:

public class Foo extends Bar {
    private boolean someBoolean = true;
    private String someStringField;
    private float someExcludedField;
    
    @java.lang.Override
    public java.lang.String toString() {
        return "Foo(super=" + super.toString() +
            ", someBoolean=" + someBoolean +
            ", someStringField=" + someStringField + ")";
    }
}

@EqualsAndHashCode

@EqualsAndHashCode Lombok 代码:

@EqualsAndHashCode(callSuper=true,exclude={"address","city","state","zip"})
public class Person extends SentientBeing {
    enum Gender { Male, Female }

    @NonNull private String name;
    @NonNull private Gender gender;
    
    private String ssn;
    private String address;
    private String city;
    private String state;
    private String zip;
}

等价于 Java 源码:

public class Person extends SentientBeing {
    
    enum Gender {
        /*public static final*/ Male /* = new Gender() */,
        /*public static final*/ Female /* = new Gender() */;
    }
    @NonNull
    private String name;
    @NonNull
    private Gender gender;
    private String ssn;
    private String address;
    private String city;
    private String state;
    private String zip;
    
    @java.lang.Override
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (o.getClass() != this.getClass()) return false;
        if (!super.equals(o)) return false;
        final Person other = (Person)o;
        if (this.name == null ? other.name != null : !this.name.equals(other.name)) return false;
        if (this.gender == null ? other.gender != null : !this.gender.equals(other.gender)) return false;
        if (this.ssn == null ? other.ssn != null : !this.ssn.equals(other.ssn)) return false;
        return true;
    }
    
    @java.lang.Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = result * PRIME + super.hashCode();
        result = result * PRIME + (this.name == null ? 0 : this.name.hashCode());
        result = result * PRIME + (this.gender == null ? 0 : this.gender.hashCode());
        result = result * PRIME + (this.ssn == null ? 0 : this.ssn.hashCode());
        return result;
    }
}

@Data

@Data Lombok 代码:

@Data(staticConstructor="of")
public class Company {
    private final Person founder;
    private String name;
    private List<Person> employees;
}

等价于 Java 源码:

public class Company {
    private final Person founder;
    private String name;
    private List<Person> employees;
    
    private Company(final Person founder) {
        this.founder = founder;
    }
    
    public static Company of(final Person founder) {
        return new Company(founder);
    }
    
    public Person getFounder() {
        return founder;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(final String name) {
        this.name = name;
    }
    
    public List<Person> getEmployees() {
        return employees;
    }
    
    public void setEmployees(final List<Person> employees) {
        this.employees = employees;
    }
    
    @java.lang.Override
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (o.getClass() != this.getClass()) return false;
        final Company other = (Company)o;
        if (this.founder == null ? other.founder != null : !this.founder.equals(other.founder)) return false;
        if (this.name == null ? other.name != null : !this.name.equals(other.name)) return false;
        if (this.employees == null ? other.employees != null : !this.employees.equals(other.employees)) return false;
        return true;
    }
    
    @java.lang.Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = result * PRIME + (this.founder == null ? 0 : this.founder.hashCode());
        result = result * PRIME + (this.name == null ? 0 : this.name.hashCode());
        result = result * PRIME + (this.employees == null ? 0 : this.employees.hashCode());
        return result;
    }
    
    @java.lang.Override
    public java.lang.String toString() {
        return "Company(founder=" + founder + ", name=" + name + ", employees=" + employees + ")";
    }
}

@Cleanup

@Cleanup Lombok 代码:

public void testCleanUp() {
    try {
        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(new byte[] {'Y','e','s'});
        System.out.println(baos.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

等价于 Java 源码:

public void testCleanUp() {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            baos.write(new byte[]{'Y', 'e', 's'});
            System.out.println(baos.toString());
        } finally {
            baos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Synchronized

@Synchronized Lombok 代码:

private DateFormat format = new SimpleDateFormat("MM-dd-YYYY");

@Synchronized
public String synchronizedFormat(Date date) {
    return format.format(date);
}

等价于 Java 源码:

private final java.lang.Object $lock = new java.lang.Object[0];
private DateFormat format = new SimpleDateFormat("MM-dd-YYYY");

public String synchronizedFormat(Date date) {
    synchronized ($lock) {
        return format.format(date);
    }
}

@SneakyThrows

@SneakyThrows Lombok 代码:

@SneakyThrows
public void testSneakyThrows() {
    throw new IllegalAccessException();
}

等价于 Java 源码:

public void testSneakyThrows() {
    try {
        throw new IllegalAccessException();
    } catch (java.lang.Throwable $ex) {
        throw lombok.Lombok.sneakyThrow($ex);
    }
}

示例

使用 Lombok 定义一个 Java Bean

import lombok.Data;
import lombok.ToString;

@Data
@ToString(exclude = "age")
public class Person {
    private String name;
    private Integer age;
    private String sex;
}

测试

Person person = new Person();
person.setName("张三");
person.setAge(20);
person.setSex("男");
System.out.println(person.toString());
// output: Person(name=张三, sex=男)

资料

Lombok 官网 | Lombok Github

IntelliJ IDEA - Lombok Plugin

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏ppjun专栏

ViewModel 源码分析

从图可以看出来,ViewModel 与 LiveData 和 Paging 是谷歌新组件,同时它是 android.arch.lifecycle 包里面的类,可...

711
来自专栏LanceToBigData

SpringBoot(四)SpringBoot中lombok使用

lombok概述 lombok简介 Lombok想要解决了的是在我们实体Bean中大量的Getter/Setter方法,以及toString, hashCo...

4049
来自专栏魂祭心

原 荐 NEO VM原理及其实现

3828
来自专栏大前端_Web

easyUI组件datagrid的二次封装

版权声明:本文为吴孔云博客原创文章,转载请注明出处并带上链接,谢谢。 https://blog.csdn.net/wkyseo/articl...

713
来自专栏happyJared

Java类库:Lombok

  前阵子闲逛的时候,留意到了Lombok这个Java第三方库,后来亲自试用了一下,还真有一种相见恨晚的感觉,对于博主这样的懒人来说,这简直是太实用了。这不趁周...

422
来自专栏chenssy

【追光者系列】HikariCP源码分析之字节码修改类库Javassist委托实现动态代理

很多人都会问HikariCP为什么那么快?之前的两篇文章【追光者系列】HikariCP源码分析之FastList 和 【追光者系列】HikariCP源码分析之C...

1362
来自专栏Java开发者杂谈

Jetty入门

总述 同tomcat一样,jetty也是一个servlet引擎,jetty的神奇之处在于,jetty不仅可以作为一个web应用的容器,它甚至还可以作为一个程序中...

3486
来自专栏开发技术

spring事务源码解析

  在spring jdbcTemplate 事务,各种诡异,包你醍醐灌顶!最后遗留了一个问题:spring是怎么样保证事务一致性的? 当然,spring事务内...

451
来自专栏Hongten

模仿Hibernate的逆向工程_java版_源码下载

在这篇blog:"Hibernate逆向工程原理_java版本"中谈到了Hibernate逆向工程原理。

894
来自专栏aoho求索

Lombok使用与原理

Lombok使用与原理 1. Lombok简介 首先 Lombok是一款Java IDE的应用工具插件,一个可以通过简单的注解形式来帮助我们简化消除一些必须有但...

3008

扫码关注云+社区