我正在使用方便的 try-with-resources 语句来关闭连接。这在大多数情况下都很有效,但只有在一种非常简单的方法中它才能正常工作。即,这里:
public boolean testConnection(SapConnection connection) {
SapConnect connect = createConnection(connection);
try ( SapApi sapApi = connect.connect() ) {
return ( sapApi != null );
} catch (JCoException e) {
throw new UncheckedConnectionException("...", e);
}
}
Run Code Online (Sandbox Code Playgroud)
sapApi 对象为非空,该方法返回 true,但从未调用 sapApi 的 close() 方法。我现在求助于使用一个工作正常的 finally 块。但这很令人费解。Java 字节码还包含对 close 的调用。有没有人见过这种行为?
编辑以澄清情况:
这是 SapApi,当然,它实现了 AutoCloseable。
class SapApi implements AutoCloseable {
@Override
public void close() throws JCoException {
connection.close(); // this line is not hit when leaving testConnection(..)
}
..
}
Run Code Online (Sandbox Code Playgroud)
下面是与 …