背景
我在IOUtils上使用了一个很好的函数,叫做 "closeQuietly" ,它关闭流,不管里面有什么。
例如:
InputStream input = null;
try
{
...
input = connection.getInputStream();
...
}
catch(Exception e)
{
}
finally
{
IOUtils.closeQuietly(input);
}
不知何故,当我在 finally 块中调用它时,它也隐藏了 Eclipse 上的警告,即“资源泄漏:'input' is not closed at this location”。
这意味着在上面的代码中,没有这样的警告。
问题
我不明白它如何将警告隐藏在自身的“外部世界”上。
我试过的
我试图通过复制这个库的代码来检查它(这里的例子),但是当我在新类上使用它时会出现警告。这没有意义...
这是我创建的示例代码,用于显示警告将发生在您自己的类上:
public class MyIOUtils {
public static void closeQuietly(final InputStream input) {
if (input == null)
return;
try {
input.close();
} catch (final IOException ioe) {
}
}
public static void closeQuietly(final OutputStream output) {
if (output == null)
return;
try {
output.close();
} catch (final IOException ioe) {
}
}
}
用法:
public class Test {
public void test() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("dummyFile.txt");
int t = 0;
--t;
if (t < 0)
return; // here you will get a warning
} catch (final FileNotFoundException e) {
} finally {
MyIOUtils.closeQuietly(inputStream);
}
}
}
这是我看到的,包括我正在安装的 Eclipse 版本:
问题
它是如何做到的?