java 当 AutoCloseable 为空时尝试使用资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35372148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:04:41  来源:igfitidea点击:

Try-With Resource when AutoCloseable is null

javatry-catchautocloseable

提问by flakes

How does the try-with feature work for AutoCloseablevariables that have been declared null?

try-with 功能如何AutoCloseable对已声明的变量起作用null

I assumed this would lead to a null pointer exception when it attempts to invoke closeon the variable, but it runs no problem:

我认为这在尝试调用close变量时会导致空指针异常,但它运行没有问题:

try (BufferedReader br = null){
    System.out.println("Test");
}
catch (IOException e){
    e.printStackTrace();
}

回答by Andy Thomas

The Java Language Specification specifies that it is closed only if non-null, in section 14.20.3. try-with-resources:

Java 语言规范在第14.20.3节中指定仅在非 null 时才关闭它尝试资源

A resource is closed only if it initialized to a non-null value.

资源仅在初始化为非空值时才关闭。

This can actually be useful, when a resource might present sometimes, and absent others.

这实际上很有用,当资源有时可能存在而其他资源可能不存在时。

For example, say you might or might not have a closeable proxy to some remote logging system.

例如,假设您可能有也可能没有某个远程日志系统的可关闭代理。

try ( IRemoteLogger remoteLogger = getRemoteLoggerMaybe() ) {
    if ( null != remoteLogger ) {
       ...
    }
}

If the reference is non-null, the remote logger proxy is closed, as we expect. But if the reference is null, no attempt is made to call close() on it, no NullPointerException is thrown, and the code still works.

如果引用为非空,则远程记录器代理关闭,正如我们所期望的。但是,如果引用为空,则不会尝试对其调用 close(),也不会抛出 NullPointerException,并且代码仍然有效。