簡體   English   中英

try-with-resources 調用 close() 失敗

[英]try-with-resources fails to call close()

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

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(..)
  }
..
}

下面是與 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);
  }
}

編輯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);
  }
}

SapApi 沒有子類。 上面的 close 方法只有一種實現。 特別是,沒有空的 close()。

為了調用 close(),SapApi 必須實現 AutoCloseable 接口,但既然我們在談論連接,那么您 SapApi 將實現拋出 IOException 的 Closable 接口更為合適。

閱讀: http : //tutorials.jenkov.com/java-exception-handling/try-with-resources.html

我不知道你的意思

這在大多數情況下效果很好

1 在 try-with-resources 中使用時,通常SapApi是關閉的

或者

2 它通常適用於SapApi以外的資源

我是根據數字 2 的假設來回答的。

Try-with-resources 只能在 Java 7 中用於實現AutoCloseable接口的資源。 所以我的第一個建議是讓您檢查SapConnectSapApi (無論它們是什么)的 API,以確定是否是這種情況。

一種猜測:也許connect返回 SapApi 的子類或代理類。 如果沒有進行任何更改,則close不執行任何操作,否則只能調用super.close()

我會把它作為答案,因為即使沒有調用任何方法,AutoCloseable 也能工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM