自动关闭HttpURLConnection(与使用资源尝试的数据库连接相同) 在这里我正在寻找关闭HttpURLConnection,而没有手动关闭ex:urlConnection.disconnect();在最后一个区块
答案 0 :(得分:0)
这并不完全相同,但是您可以为Autocloseable
写一个包装器类。
class AutocloseWrapper<T> implements Autocloseable {
T wrapped;
Consumer<T> closeMethod;
public AutocloseWrapper(T wrapped, Consumer<T> closeMethod) {
this.wrapped = wrapped; this.closeMethod = closeMethod;
}
public void close() {
closeMethod.accept(wrapped);
}
}
然后用
private void yourMethod() {
HttpUrlConnection connection = createConnection();
try (AutocloseWrapper wrapper = new AutocloseWrapper(connection, HttpUrlConnection::disconnect)) {
// do your stuff with the connection
}
// connection.disconnect() will have been called here
}