try-with-resources 调用 close() 失败

avi*_*idD 5 java try-with-resources sapjco3

我正在使用方便的 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)

下面是与 testConnection(..) 同一个类中的另一个方法。这里 SapApi.close() 在返回之前被调用。

@Override
public List<Characteristic> selectCharacteristics(SapConnect aConnection,   InfoProvider aInfoProvider) {
  try (SapApi sapi = aConnection.connect()) {
    return sapi.getCharacteristics(aInfoProvider);
  } catch ( Exception e ) {
    throw new UncheckedConnectionException(e.getMessage(), e);
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑2:这是 SapConnect.connect():

SapApi connect() {
  try {
    ... // some setup of the connection
    return new SapApi(this); // single return statement
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

SapApi 没有子类。上面的 close 方法只有一种实现。特别是,没有空的 close()。

APD*_*APD 1

我不知道你的意思

这在大多数情况下都很有效

1 通常SapApi在 try-with-resources 中使用时是关闭的

或者

2 它通常适用于除SapApi

我是根据第二个假设来回答的。

Try-with-resources 仅适用于 Java 7 中实现AutoCloseable接口的资源。因此,我的第一个建议是检查 API (SapConnect无论SapApi它们是什么)以确定情况是否如此。