Lombok插件

Lombok简介

Lombok是一款好用顺手的工具,就像Google Guava一样,在此予以强烈推荐,每一个Java工程师都应该使用它。Lombok是一种Java™实用工具,可用来帮助开发人员消除Java的冗长代码,尤其是对于简单的Java对象(POJO)。它通过注释实现这一目的。通过在开发环境中实现Lombok,开发人员可以节省构建诸如hashCode()和equals()这样的方法以及以往用来分类各种accessor和mutator的大量时间。
Lombok官网地址:https://projectlombok.org/ 里面还提供了一个简短的学习视频。
 
 
安装Lombok

IntelliJ安装Lombok

通过IntelliJ的插件中心安装

 

Lombok用法

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

 

Lombok使用示例

1.val示例 

1 public static void main(String[] args) {
2     val sets = new HashSet<String>();
3     val lists = new ArrayList<String>();
4     val maps = new HashMap<String, String>();
5     //=>相当于如下
6     final Set<String> sets2 = new HashSet<>();
7     final List<String> lists2 = new ArrayList<>();
8     final Map<String, String> maps2 = new HashMap<>();
9 }

2. @NonNull示例

 1 public void notNullExample(@NonNull String string) {
 2     string.length();
 3 }
 4 //=>相当于
 5 public void notNullExample(String string) {
 6     if (string != null) {
 7         string.length();
 8     } else {
 9         throw new NullPointerException("null");
10     }
11 }

3. @Cleanup示例

 1 public static void main(String[] args) {
 2     try {
 3         @Cleanup InputStream inputStream = new FileInputStream(args[0]);
 4     } catch (FileNotFoundException e) {
 5         e.printStackTrace();
 6     }
 7     //=>相当于
 8     InputStream inputStream = null;
 9     try {
10         inputStream = new FileInputStream(args[0]);
11     } catch (FileNotFoundException e) {
12         e.printStackTrace();
13     } finally {
14         if (inputStream != null) {
15             try {
16                 inputStream.close();
17             } catch (IOException e) {
18                 e.printStackTrace();
19             }
20         }
21     }
22 }

4. @Getter/@Setter示例

1 @Setter(AccessLevel.PUBLIC)
2 @Getter(AccessLevel.PROTECTED)
3 private int id;
4 private String shap;

5. @ToString示例

 1 @ToString(exclude = "id", callSuper = true, includeFieldNames = true)
 2 public class LombokDemo {
 3     private int id;
 4     private String name;
 5     private int age;
 6     public static void main(String[] args) {
 7         //输出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
 8         System.out.println(new LombokDemo());
 9     }
10 }

6. @EqualsAndHashCode示例

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

7. @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor示例

 1 @NoArgsConstructor
 2 @RequiredArgsConstructor(staticName = "of")
 3 @AllArgsConstructor
 4 public class LombokDemo {
 5     @NonNull
 6     private int id;
 7     @NonNull
 8     private String shap;
 9     private int age;
10     public static void main(String[] args) {
11         new LombokDemo(1, "circle");
12         //使用静态工厂方法
13         LombokDemo.of(2, "circle");
14         //无参构造
15         new LombokDemo();
16         //包含所有参数
17         new LombokDemo(1, "circle", 2);
18     }
19 }

8. @Data示例

 1 import lombok.Data;
 2 @Data
 3 public class Menu {
 4     private String shopId;
 5     private String skuMenuId;
 6     private String skuName;
 7     private String normalizeSkuName;
 8     private String dishMenuId;
 9     private String dishName;
10     private String dishNum;
11     //默认阈值
12     private float thresHold = 0;
13     //新阈值
14     private float newThresHold = 0;
15     //总得分
16     private float totalScore = 0;
17 }

9. @Value示例

 1 @Value
 2 public class LombokDemo {
 3     @NonNull
 4     private int id;
 5     @NonNull
 6     private String shap;
 7     private int age;
 8     //相当于
 9     private final int id;
10     public int getId() {
11         return this.id;
12     }
13     ...
14 }

10. @Builder示例

 1 @Builder
 2 public class BuilderExample {
 3     private String name;
 4     private int age;
 5     @Singular
 6     private Set<String> occupations;
 7     public static void main(String[] args) {
 8         BuilderExample test = BuilderExample.builder().age(11).name("test").build();
 9     }
10 }

11. @SneakyThrows示例

 1 import lombok.SneakyThrows;
 2 import java.io.FileInputStream;
 3 import java.io.FileNotFoundException;
 4 import java.io.InputStream;
 5 import java.io.UnsupportedEncodingException;
 6 public class Test {
 7     @SneakyThrows()
 8     public void read() {
 9         InputStream inputStream = new FileInputStream("");
10     }
11     @SneakyThrows
12     public void write() {
13         throw new UnsupportedEncodingException();
14     }
15     //相当于
16     public void read() throws FileNotFoundException {
17         InputStream inputStream = new FileInputStream("");
18     }
19     public void write() throws UnsupportedEncodingException {
20         throw new UnsupportedEncodingException();
21     }
22 }

12. @Synchronized示例

 1 public class SynchronizedDemo {
 2     @Synchronized
 3     public static void hello() {
 4         System.out.println("world");
 5     }
 6     //相当于
 7     private static final Object $LOCK = new Object[0];
 8     public static void hello() {
 9         synchronized ($LOCK) {
10             System.out.println("world");
11         }
12     }
13 }

13. @Getter(lazy = true)

 1 public class GetterLazyExample {
 2     @Getter(lazy = true)
 3     private final double[] cached = expensive();
 4     private double[] expensive() {
 5         double[] result = new double[1000000];
 6         for (int i = 0; i < result.length; i++) {
 7             result[i] = Math.asin(i);
 8         }
 9         return result;
10     }
11 }

相当于如下所示

 1 import java.util.concurrent.atomic.AtomicReference;
 2 public class GetterLazyExample {
 3     private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();
 4     public double[] getCached() {
 5         java.lang.Object value = this.cached.get();
 6         if (value == null) {
 7             synchronized (this.cached) {
 8                 value = this.cached.get();
 9                 if (value == null) {
10                     final double[] actualValue = expensive();
11                     value = actualValue == null ? this.cached : actualValue;
12                     this.cached.set(value);
13                 }
14             }
15         }
16         return (double[]) (value == this.cached ? null : value);
17     }
18     private double[] expensive() {
19         double[] result = new double[1000000];
20         for (int i = 0; i < result.length; i++) {
21             result[i] = Math.asin(i);
22         }
23         return result;
24     }
25 }

 

 

 

 

 

posted @ 2018-06-09 15:35  N!CE波  阅读(471)  评论(0编辑  收藏  举报