Lombok插件中常用注解

  lombok 提供了简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 java 代码。


@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法

@Setter:注解在属性上;为属性提供 setting 方法

@Getter:注解在属性上;为属性提供 getting 方法

@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象

@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法

@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法

@NonNull:注解在参数上 如果该参数为null 会throw new NullPointerException(参数名);

@Cleanup:注释在引用变量前:自动回收资源 默认调用close方法

  @Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);

  @Cleanup InputStream in = new FileInputStream(args[0]);

  @Cleanup OutputStream out = new FileOutputStream(args[1]);


介绍一下Lombok中的Cleanup这个annotation , 他的方便之处,大家在代码中一睹风采:

使用前:

import java.io.*;  
  
public class CleanupExample {  
  public static void main(String[] args) throws IOException {  
    InputStream in = new FileInputStream(args[0]);  
    try {  
      OutputStream out = new FileOutputStream(args[1]);  
      try {  
        byte[] b = new byte[10000];  
        while (true) {  
          int r = in.read(b);  
          if (r == -1) break;  
          out.write(b, 0, r);  
        }  
      } finally {  
        if (out != null) {  
          out.close();  
        }  
      }  
    } finally {  
      if (in != null) {  
        in.close();  
      }  
    }  
  }  
}  

使用后:

import lombok.Cleanup;  
import java.io.*;  
  
public class CleanupExample {  
  public static void main(String[] args) throws IOException {  
    @Cleanup InputStream in = new FileInputStream(args[0]);  
    @Cleanup OutputStream out = new FileOutputStream(args[1]);  
    byte[] b = new byte[10000];  
    while (true) {  
      int r = in.read(b);  
      if (r == -1) break;  
      out.write(b, 0, r);  
    }  
  }  
}

单单从代码的行数上面就可以知道已经精简了不少,同时,代码的可读性也进一步提高。从代码中我们可以容易的看出,@Cleanup的作用就是在当前变量不在有效范围内的时候,对其进行自动的资源回收。在Java中的Stream上使用Cleanup Annotation,就是对其调用close方法。

原文:https://blog.csdn.net/dc2222333/article/details/78319687 

猜你喜欢

转载自blog.csdn.net/qq_41084324/article/details/84540322