Lombok中的关闭资源的注解@Cleanup,发现这个注解的时候我还兴高采烈的:终于不用琢磨着处理资源关闭的事了。捉摸了一下还是试验一下,看看这个注解编译出来到底是个啥样的,结果发现问题~~~~
作用于变量,保证该变量代表的资源会被自动关闭,默认调用资源的close()方法,如果该资源有其它关闭方法,可使用@Cleanup(“methodName”)来指定。
这里***是个坑!!!!!!
按照这里的参考文档:@Cleanup (projectlombok.org)
把他的代码搞过来编译一下~
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);
}
}
}
瞅瞅这是个啥~ 吃掉了好多东西
与他文档里面写的有很大差异
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();
}
}
}
}
所得出来的结果差异巨大~
让我再试试最短的 就只创建一下
package org.example;
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream("some/file");
}
}
好的 没有区别 这还是和他描述的不一致~
再修改一下 不想抛出异常想直接解决他~
package org.example;
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) {
try {
@Cleanup InputStream in = new FileInputStream("some/file");
}catch (IOException e){
e.printStackTrace();
}
}
}
出来是这样的
与我想的
package org.example;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class CleanupExample {
public static void main(String[] args) {
InputStream in = null;
try {
in = new FileInputStream("some/file");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这样的相差甚远。
使用@Cleanup 关闭的这个中间如果有其他问题 资源就不会关闭~ 这不瞎搞嘛,本身就是想偷懒少写几行。这功能都没实现~ 太坑了!!
然后我在文章末尾看到这样一段字~~
英语不行 上翻译!!
这是啥 这是啥~ 啊?? 好原来你知道这玩意的问题在哪是吧~~ 好好好~ 这样玩!!!!