在实现AutoCloseable以使用
Java 7 try-with-resources语句时,我想知道try块中是否存在异常.例如.:
class C implements AutoCloseable {
@Override
public void close() {
if (exceptionOccurred)
something();
else
somethingElse();
}
}
为了说明这一点:
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
;
}
现在,从了解how the try-with-resources statement translates to bytecode,我想这是不可能的.但是有没有(可靠!)技巧通过instrumentation / reflection /一些未记录的编译器功能,允许我从AutoCloseable.close()中访问上面的RuntimeException?
注意:我是一名API设计师,我无法控制API使用者的资源尝试代码.因此,必须在AutoCloseable站点上完成实现
解决方法
执行此操作的常规方法是在try块的末尾显式调用.例如:
try (CustomTransaction transaction = ...) {
// Do something which might throw an exception...
transaction.commitOnClose();
}
然后在结束时,你要么根据是否调用commitOnClose()而中止事务或提交它.
它不是自动的,但实现起来非常简单 – 而且阅读起来非常简单.