当我在main方法中打开资源时
WebClient webClient = new WebClient();
Eclipse向我显示警告Resource leak: 'webClient' is never closed
。所以我需要通过
webClient.close().
但是当我从方法
获得WebClient
时
WebClient webClient = getWebCLient()
public static WebClient getWebClient() {
WebClient webClient = new WebClient();
...
return webClient;
}
我没有收到这样的警告。为什么?
答案 0 :(得分:1)
在这种情况下,IDE并不够聪明,不能发出警告。绝不意味着WebClient
不再被关闭。
如果WebClient
实现AutoCloseable,请考虑将getWebClient()
的调用包装到try-with-resource中以便自动关闭
try (WebClient wc = getWebClient()) {
...
}