将资源移出试用

问题描述

我想创建一个包装资源的类实例。问题是:构造函数抛出时,资源会丢失。我正在尝试为此找到解决方案。 Try-with-resource是一种看起来不错的构造,但是我无法将资源移出它。

例如,包装HTTP客户端的服务客户端:

class ServiceClient implements Closeable {
  ServiceClient(ClosableHTTPClient client) { /* ... */ }
  public close() { client.close() }

  public ServiceClient create(String url) throws IOException {
    try (ClosableHTTPClient client = createHttpClient(url)) {
      return new ServiceClient(client);
    }  // make try-with do not close `client` on success
  }

  public ClosableHTTPClient createHttpClient(String url) {
    return HttpClientBuilder.create()
        .setConnectionManager(createClosableConnectionManager()) // must be closed,when `build` throws 
        .build();
  }
}

解决方法

引发异常的构造函数。

<div class="budget-item" [ngClass]="{ 'income' : isIncome,expense : !isIncome }" >
    <div class="description" >
        <p>{{item.description}}</p>
    </div>
    <div class="amount">
        <p>{{item.amount}}</p>
    </div>
</div>

唯一的解决方案是处理构造函数中引发的任何异常。 标准的Java类有时会忘记事件(具有负容量的BufferedReader不会关闭其包装的阅读器)。