Lombok 之 Cleanup

LomBok 的相关目录已经整理出来,希望大家可以根据需求自助学习,好工具要大家分享:

@Cleanup     

@Getter, @Setter

@ToString

@EqualsAndHashCode

@Constructor

@Data & @Value

@SneakyThrows

@Synchronized

@Getter(lazy=true)

@Log

介绍一下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方法。

但是,请大家注意,Cleanup 存在一个小问题:

官网给出了提示,如果你的代码中出现了异常,那么会触发cleanup方法抛出异常,导致把原始异常吞掉,这样就导致你在上层不知道发生了什么事情,这个事情很严重啊,但是如果说你是在调用close方法的时候出了异常,那么Cleanup这个annotation是不会把异常吞掉的。 同时,官网也指出,作业也没有找到更好的方式去解决这个问题,如果他们找到了会立刻fix这个问题,否则也就只能等待Java 有可能在Update的时候出现新的解决方案。

猜你喜欢

转载自himichaelchu.iteye.com/blog/2124327