Luk*_*der 7 java try-with-resources autocloseable
在实现AutoCloseable使用Java 7 try-with-resources语句时,我想知道try块中是否存在异常.例如:
class C implements AutoCloseable {
@Override
public void close() {
if (exceptionOccurred)
something();
else
somethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
为了说明这一点:
try (C c = new C()) {
// This should cause a call to "something()"
if (something)
throw new RuntimeException();
// This should cause a call to "somethingElse()"
else
;
}
Run Code Online (Sandbox Code Playgroud)
现在,从了解try-with-resources语句如何转换为字节码,我想这是不可能的.但有没有(可靠!)技巧通过检测/反射/一些未记录的编译器功能,允许我RuntimeException从内部访问上述AutoCloseable.close()?
注意:我是一名API设计师,我无法控制API使用者的资源尝试代码.因此必须在AutoCloseable现场完成实施
Jon*_*eet 10
执行此操作的常规方法是在try块的末尾显式调用.例如:
try (CustomTransaction transaction = ...) {
// Do something which might throw an exception...
transaction.commitOnClose();
}
Run Code Online (Sandbox Code Playgroud)
然后close,根据是否commitOnClose()已被调用,您可以中止事务或提交事务.
它不是自动的,但实现起来非常简单 - 而且阅读起来非常简单.