一、安装

  • eclipse

下载:https://projectlombok.org/
       双击安装即可。

重启eclipse/myeclipse

        如果有报错,clean一下项目就ok了。

  • intellij

安装lombok插件即可
      setting→plugins→搜lombok→安装(需要重启)

重启intelliJ

二、Lombok用法

注解说明
  • val:用在局部变量前面,相当于将变量声明为final
  • @NonNull:给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出NPE(NullPointerException)
  • @Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成try-finally这样的代码来关闭流
  • @Getter/@Setter:用在属性上,再也不用自己手写setter和getter方法了,还可以指定访问范围
  • @ToString:用在类上,可以自动覆写toString方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除id属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的toString方法,包含所有属性
  • @EqualsAndHashCode:用在类上,自动生成equals方法和hashCode方法
  • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有@NonNull属性作为参数的构造函数,如果指定staticName = “of”参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多
  • @Data:注解在类上,相当于同时使用了@ToString@EqualsAndHashCode@Getter@Setter@RequiredArgsConstrutor这些注解,对于POJO类十分有用
  • @Value:用在类上,是@Data的不可变形式,相当于为属性添加final声明,只提供getter方法,而不提供setter方法
  • @Builder:用在类、构造器、方法上,为你提供复杂的builder APIs,让你可以像如下方式一样调用Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();更多说明参考Builder
  • @SneakyThrows:自动抛受检异常,而无需显式在方法上使用throws语句
  • @Synchronized:用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性$lock$LOCK,而java中的synchronized关键字锁对象是this,锁在this或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁this或者类对象,这可能会导致竞争条件或者其它线程错误
  • @Getter(lazy=true):可以替代经典的Double Check Lock样板代码
  • @Log:根据不同的注解生成不同类型的log对象,但是实例名称都是log,有六种可选实现类
    • @CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
    • @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());
    • @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);
    • @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
    • @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
    • @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);

三、代码示例

  • val
  • val示例

    public static void main(String[] args) {
    val sets = new HashSet<String>();
    val lists = new ArrayList<String>();
    val maps = new HashMap<String, String>();
    //=>相当于如下
    final Set<String> sets2 = new HashSet<>();
    final List<String> lists2 = new ArrayList<>();
    final Map<String, String> maps2 = new HashMap<>();
    }
  • @NonNull示例

    public void notNullExample(@NonNull String string) {
string.length();
}
    //=>相当于
public void notNullExample(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
  • @Cleanup示例

    public static void main(String[] args) {
    try {
    @Cleanup InputStream inputStream = new FileInputStream(args[0]);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    //=>相当于
    InputStream inputStream = null;
    try {
    inputStream = new FileInputStream(args[0]);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } finally {
    if (inputStream != null) {
    try {
    inputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
  • @Getter/@Setter示例

    @Setter(AccessLevel.PUBLIC)
    @Getter(AccessLevel.PROTECTED)
    private int id;
    private String shap;
  • @ToString示例

     
    @ToString(exclude = "id", callSuper = true, includeFieldNames = true)
    public class LombokDemo {
    private int id;
    private String name;
    private int age; public static void main(String[] args) {
    //输出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
    System.out.println(new LombokDemo());
    }
    }
  • @EqualsAndHashCode示例

     
    @EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
    public class LombokDemo {
    private int id;
    private String shap;
    }

  • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor示例

    @NoArgsConstructor
    @RequiredArgsConstructor(staticName = "of")
    @AllArgsConstructor
    public class LombokDemo {
    @NonNull
    private int id;
    @NonNull
    private String shap;
    private int age;
    public static void main(String[] args) {
    new LombokDemo(1, "circle");
    //使用静态工厂方法
    LombokDemo.of(2, "circle");
    //无参构造
    new LombokDemo();
    //包含所有参数
    new LombokDemo(1, "circle", 2);
    }
    }
  • @Data示例

    import lombok.Data;
    @Data
    public class Menu {
    private String shopId;
    private String skuMenuId;
    private String skuName;
    private String normalizeSkuName;
    private String dishMenuId;
    private String dishName;
    private String dishNum;
    //默认阈值
    private float thresHold = 0;
    //新阈值
    private float newThresHold = 0;
    //总得分
    private float totalScore = 0;
    }

    在IntelliJ中按下Ctrl+F12就可以看到Lombok已经为我们自动生成了一系列的方法。

  • @Value示例

    @Value
    public class LombokDemo {
    @NonNull
    private int id;
    @NonNull
    private String shap;
    private int age;
    //相当于
    private final int id;
    public int getId() {
    return this.id;
    }
    ...
    }
  • @Builder示例

    @Builder
    public class BuilderExample {
    private String name;
    private int age;
    @Singular
    private Set<String> occupations;
    public static void main(String[] args) {
    BuilderExample test = BuilderExample.builder().age(11).name("test").build();
    }
    }
  • @SneakyThrows示例

    import lombok.SneakyThrows;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    public class Test {
    @SneakyThrows()
    public void read() {
    InputStream inputStream = new FileInputStream("");
    }
    @SneakyThrows
    public void write() {
    throw new UnsupportedEncodingException();
    }
    //相当于
    public void read() throws FileNotFoundException {
    InputStream inputStream = new FileInputStream("");
    }
    public void write() throws UnsupportedEncodingException {
    throw new UnsupportedEncodingException();
    }
    }
  • @Synchronized示例

    public class SynchronizedDemo {
    @Synchronized
    public static void hello() {
    System.out.println("world");
    }
    //相当于
    private static final Object $LOCK = new Object[0];
    public static void hello() {
    synchronized ($LOCK) {
    System.out.println("world");
    }
    }
    }
  • @Getter(lazy = true)

    public class GetterLazyExample {
@Getter(lazy = true)
private final double[] cached = expensive();
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
 
    import java.util.concurrent.atomic.AtomicReference;
public class GetterLazyExample {
private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized (this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive();
value = actualValue == null ? this.cached : actualValue;
this.cached.set(value);
}
}
}
return (double[]) (value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}

使用Lombok简化你的代码的更多相关文章

  1. Idea使用Lombok简化实体类代码

    引入相应的maven包 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lo ...

  2. lombok 简化java代码注解

    lombok 简化java代码注解 安装lombok插件 以intellij ide为例 File-->Setting-->Plugins-->搜索"lombok plug ...

  3. Lombok简化Java代码

    导包:import lombok.Data; Lombok简化Java代码: 在Lombok中,生成构造方法的annotation一共有三个:@NoArgsConstructor, @Required ...

  4. 使用建造者模式和Lombok简化代码

    在项目开发中,我们经常需要构建对象.常见的做法有getter/setter,或者构造器构建对象. 可能会有人写出类似如下的代码: Company company=new Company(); comp ...

  5. 【lombok】使用lombok注解,在代码编写过程中可以调用到get/set方法,但是在编译的时候无法通过,提示找不到get/set方法

    错误如题:使用lombok注解,在代码编写过程中可以调用到get/set方法,但是在编译的时候无法通过,提示找不到get/set方法 报错如下: 解决方法: 1.首先查看你的lombok插件是否下载安 ...

  6. 第7.24节 Python案例详解:使用property函数定义属性简化属性访问代码实现

    第7.24节 Python案例详解:使用property函数定义属性简化属性访问代码实现 一.    案例说明 本节将通过一个案例介绍怎么使用property定义快捷的属性访问.案例中使用Rectan ...

  7. 使用 lombok 简化代码

    使用前的准备 1.Lombok 是一种 Java™ 实用工具,可用来帮助开发人员消除 Java 的冗长,尤其是对于简单的 Java 对象(POJO).它通过注解实现这一目的.  <1>添加 ...

  8. eclipse使用lombok简化java代码

    可以利用注解来代替getter.setter.toString.hashCode.构造方法等,简化代码开发. 具体用法 https://www.cnblogs.com/qnight/p/8997493 ...

  9. Lombok简化Java代码的好工具

    lombok 的官方网址:http://projectlombok.org/ 关于lombok 的介绍,有几篇帖子,写得都很好 比如 http://www.blogjava.net/fancydeep ...

随机推荐

  1. HTML 5 服务器发送事件

    接收 Server-Sent 事件通知 EventSource 对象用于接收服务器发送事件通知: 实例 var source=new EventSource("demo_sse.php&qu ...

  2. HDU3466 背包DP

    Proud Merchants Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others) ...

  3. artdialog4.1.7 中父页面给子页面传值

    artdialog4.1.7中父页面给子页面传值时看了一些网友的解决方法: 在父页面声明全局变量 var returnValue=“ ”,子页面用art.dialog.opener.returnVal ...

  4. IP地址的分类与寻址

    IP地址:有一种标识符,被TCP/IP协议簇的IP层用来标识 连接到因特网的设备.IP协议的第4版IPv4地址是32位地址,是连接地址,定义了每一个连接到因特网上的设备(可以认为是主机的别名),而不是 ...

  5. jQuery上定义插件并重设插件构造函数

    插件alert的全部代码,每个插件都定义在如下类似的作用域中: +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ========= ...

  6. [troubleshoot][daily][archlinux][pacman] pacman 与 pip 包文件冲突

    今天滚系统,再次遭遇包冲突: (/) checking % error: failed to commit transaction (conflicting files) python2-reques ...

  7. C# jquery webservices 跨域调用的问题解决方案

    前台代码: <script src="js/jquery-1.9.1.min.js" type="text/javascript"></scr ...

  8. Oracle序列和索引

    序列和索引 一.序列 1.序列的概念: 序列(Sequence)是用来生成连续的整数数据的对象.它常常用来作为主键的增长列,可以升序,也可以降序. 2.创建序列: 语法:创建序列           ...

  9. LeetCode Generalized Abbreviation

    原题链接在这里:https://leetcode.com/problems/generalized-abbreviation/ 题目: Write a function to generate the ...

  10. Jmeter多机并发压测IP地址问题

    meter.engine.RemoteJMeterEngineImpl: Local IP address=192.168.56.1 不能成功链家到相应的压力机 解决步骤: 1.找到jmeter.ba ...