Lombok

Lombok

Lombok介绍

官网

https://projectlombok.org/

Lombok是什么

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

原理

JSR 269:插件化注解处理API(Pluggable Annotation Processing API)

JDK6提供的特性,在 Javac编译期利用注解搞事情

安装Lombok

导入依赖

 <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <version>1.18.12</version>
 </dependency>

安装IDEA插件

  1. File > Settings > Plugins

  2. 搜索 Lombok进行安装

Lombok常用注解

image-20200912181913344

@NoArgsConstructor @RequiredArgsConstructor @AllArgsConstructor

  1. @NoArgsConstructor : 用于生成空参构造函数

  2. @RequiredArgsConstructor :用于生成被final、@@NonNull修饰的字段的构造函数

  3. @AllArgsConstructor :用于生成全参构造函数

@Getter / @Setter

  1. 用于给生成get、set方法。

  2. 可以作用在类上和成员变量上。

  3. 可以通过AccessLevel修改方法的访问修饰符,所以对不需要生成get、set方法的成员变量,在其上方添加@Getter(AccessLevel.NONE)@Setter(AccessLevel.NONE)即可。

  4. 该注解只作用于成员变量上,对被static修饰的变量,不会为其产生相对应的get、set方法,对被final修饰的变量,只会为其生成get方法。

@ToString

  1. 用于生成toString方法

  2. 只能作用于类上

  3. 排除某些字段:@ToString(exclude = {"username","password"})

  4. 一定要包含某些字段,如静态变量:@ToString( of = {"username","password"})

@EqualsAndHashCode

  1. 用于生成equals、canEqual、hashCode方法

  2. 同样可以使用exclude 和 of 来指定需要进行判断字段

@NonNull

  1. 用于生成判断空值校验语句

  2. 可以添加在方法参数列表中或者成员变量中

@Data

  1. 集成了四个注解,分别是@RequiredArgsConstructor、

@Getter / @Setter、@ToString、@EqualsAndHashCode

@Builder

  1. 构造内部类,实现流式编程

  2.  DemoDataBuilder builder = DemoData.builder().string("String").date(new Date()).doubleData(3.14);

@Cleanup

常规写法:

 FileInputStream in = null;
 FileOutputStream out = null;
 
 try {
     in = new FileInputStream("filepath");
     out = new FileOutputStream("path2");
     byte[] b = new byte[1000];
 
     while (true) {
         int r = in.read(b);
         if (r == -1) {
             return;
        }
 
         out.write(b, 0, r);
    }
 } catch (Exception e) {
     e.printStackTrace();
 } finally {
     if (in != null) {
         try {
             in.close();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
     if (out != null) {
         try {
             out.close();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
 
 }

使用注解:

 @Cleanup InputStream in = new FileInputStream("filepath");
 @Cleanup OutputStream out = new FileOutputStream("path2");
 byte[] b = new byte[1000];
 while (true) {
     int r = in.read(b);
     if (r == -1) break;
     out.write(b, 0, r);
 }

 

 

原文地址:https://www.cnblogs.com/---------zjh---------/p/13669083.html