博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lombok 使用小结
阅读量:6718 次
发布时间:2019-06-25

本文共 7676 字,大约阅读时间需要 25 分钟。

Lombok 使用小结

Lombok 简介

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

Lombok 安装

使 IntelliJ IDEA 支持 Lombok 方式如下:

(1)Intellij 设置支持注解处理

点击 File > Settings > Build > Annotation Processors

勾选 Enable annotation processing

(2)安装插件

点击 Settings > Plugins > Browse repositories

查找 Lombok Plugin 并进行安装

重启 IntelliJ IDEA

(3)将 lombok 添加到 pom 文件

org.projectlombok
lombok
1.16.8

Lombok 使用

API

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

@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

Lombok 代码:

@Getter @Setter @NonNullprivate List
members;

等价于 Java 源码:

@NonNullprivate List
members;public Family(@NonNull final List
members) { if (members == null) throw new java.lang.NullPointerException("members"); this.members = members;}@NonNullpublic List
getMembers() { return members;}public void setMembers(@NonNull final List
members) { if (members == null) throw new java.lang.NullPointerException("members"); this.members = members;}

@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

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

Lombok 代码:

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

等价于 Java 源码:

public class Company {    private final Person founder;    private String name;    private List
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
getEmployees() { return employees; } public void setEmployees(final List
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

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

Lombok 代码:

private DateFormat format = new SimpleDateFormat("MM-dd-YYYY");@Synchronizedpublic 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

Lombok 代码:

@SneakyThrowspublic 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=男)

示例源码

完整示例:

引用和引申

引申

参考

转载地址:http://xmkmo.baihongyu.com/

你可能感兴趣的文章
最新发布:数据库防火墙技术市场调研报告
查看>>
AI如何为安防赋能?具体场景案例解析
查看>>
揭秘“史上最严高考”背后的高科技手段
查看>>
百分点:在线旅游阿里去啊购买转化最高
查看>>
“互联网+”改变传统教育模式
查看>>
阿里巴巴发布物联网平台:不止互动 更能互懂
查看>>
威胁情报工具:更快?更聪明?
查看>>
荷兰Serverius数据中心如何逆袭运营困境
查看>>
移动后端即服务带给我们什么?
查看>>
JS的运行机制
查看>>
PyCharm - Linux下最好的Python IDE
查看>>
NB-IoT来了!网络还差两个月启用,芯片和平台已经准备好了
查看>>
卢东:智能路由,家庭的数据中心
查看>>
智能家庭本周锋闻:小米推智能插座等四件新品,“真智能家居”?
查看>>
C#程序员经常用到的10个实用代码片段
查看>>
WebP支持:超乎你想象
查看>>
XSS与XSSI区别何在?
查看>>
Wink Hub:老牌家居商的智能中控平台
查看>>
云存储时代更好的选择,你的数据由你主宰
查看>>
快速迭代的互联网研发模式下测试如何突破?
查看>>