【发布时间】:2020-09-11 09:30:08
【问题描述】:
我想创建一个包装资源的类实例。问题:当构造函数抛出时,资源就丢失了。我正在尝试为此找到解决方案。 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();
}
}
【问题讨论】:
-
您当前的伪代码没有意义。到
create完成时,它创建的东西包含一个已关闭客户端的包装器。 Try-with-resources 是在资源完成时总是 关闭资源的东西。这似乎是你想要的相反。但是我不认为我理解你的问题 -
@Michael 这是我的问题:我希望它只在存在异常时关闭它。