@NonNull
自动管理输入输出流等各种需要释放的资源,确保安全地调用close方法。
1、如何使用
- 声明的资源前加上@Cleanup。
- 释放资源的方法名不是close,也可以指定要调用的方法名。
2、代码示例
例1:取自Lombok官网,加在有close的方法的资源上。
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);
}
}
}
编译后:自动释放了资源。
例2:自定义资源释放。
public class Door {
/**
* 门是否打开
* true : 打开
* false : 关闭
*/
private boolean openStatus;
public Door(boolean openStatus) {
this.openStatus = openStatus;
}
public Door() {
this.openStatus = true;
System.out.println("初始化时,门的状态默认是-打开 ");
}
public void function() {
System.out.println("调用该对象的某一个或者多个方法ing");
}
public void shut() {
System.out.println("门的状态是-" + (this.openStatus ? "打开" : "关闭"));
this.openStatus = false;
System.out.println("门的状态是-" + (this.openStatus ? "打开" : "关闭"));
}
public static void main(String[] args) {
@Cleanup("shut")
Door door = new Door();
door.function();
}
}
编译后:自动添加释放了资源所用的shut方法。
输出结果: