简化开发|Lombok神器带你消除冗余代码

 前言

Lombok是一款Java开发插件,使得Java开发者可以通过其定义的一些注解来消除业务过程中冗余的代码,尤其是简单的Java模型对象(POJO)。而当我们如果在开发环境中使用Lombok开发插件后,可以省出重复构建,诸如hashCode和equals这样的方法以及各种业务对象模型的accessor和ToString等方法的大量时间。对于这些方法,它能够在编译源代码期间自动帮我们生产这些方法,并没有如反射那样降低程序的性能。本文将带大家详细介绍关于Lombok的使用以及原理。

1. Lombok的概念

「概念:」

Lombok是一种Java实用工具,可以用来帮助开发人员消除冗余的代码,对于一些简单的Java对象(POJO),它通过注释实现这一目的。

2、Lombok的安装

「安装步骤:」

在IDEA的插件Plugins中搜索Lombok

安装Lombok

「注意:」

在使用Lombok注解的时候记得要导入Lombok.jar包到工程,Maven Project的话,要在pom.xml中添加依赖

 
 
 
 
  1.  
  2.     org.projectlombok 
  3.     lombok 
  4.     1.16.8 
  5.  

3、Lombok注解说明

「常用注解:」

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

4、Lombok代码示范

「代码示例:」

val将变量声明final类型

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

@Nonnull为方法和构造函数的参数提供非空检查

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

@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.     } 

@Getter/@Setter对类的属性字段自动生成Get/Set方法

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

@ToString为类生成一个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.     } 

@EqualsAndHashCode为类生成equals和hasCode方法

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

@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.     } 

@Data在类上使用,相当于同时使用@ToString、

@EqualsAndHashCode、@Getter、@Setter和

@RequiredArgsConstructor这些注解

 
 
 
 
  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; 

@Value为属性添加final声明

 
 
 
 
  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.     ... 

@Builder提供构建值对象方式

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

@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.     } 

@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.     } 

@Getter(lazy=true)可以替代经典的Double check Lock样板代码

 
 
 
 
  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.  
  12. // 相当于如下所示:  
  13.  
  14. import java.util.concurrent.atomic.AtomicReference; 
  15. public class GetterLazyExample { 
  16.     private final AtomicReference cached = new AtomicReference<>(); 
  17.     public double[] getCached() { 
  18.         java.lang.Object value = this.cached.get(); 
  19.         if (value == null) { 
  20.             synchronized (this.cached) { 
  21.                 value = this.cached.get(); 
  22.                 if (value == null) { 
  23.                     final double[] actualValue = expensive(); 
  24.                     value = actualValue == null ? this.cached : actualValue; 
  25.                     this.cached.set(value); 
  26.                 } 
  27.             } 
  28.         } 
  29.         return (double[]) (value == this.cached ? null : value); 
  30.     } 
  31.     private double[] expensive() { 
  32.         double[] result = new double[1000000]; 
  33.         for (int i = 0; i < result.length; i++) { 
  34.             result[i] = Math.asin(i); 
  35.         } 
  36.         return result; 
  37.     } 

@Log根据不同的注解生成不同类型的log对象

 
 
 
 
  1. * @CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); 
  2. * @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); 
  3. * @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); 
  4. * @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); 
  5. * @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); 
  6. * @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class); 

结语

本篇关于Lombok的介绍就先到这里结束了,后续会出更多关于Lombok系列更多文章,谢谢大家支持!

文章标题:简化开发|Lombok神器带你消除冗余代码
转载来于:http://www.hantingmc.com/qtweb/news47/343747.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联