简体   繁体   English

当AutoCloseable为null时,尝试使用资源

[英]Try-With Resource when AutoCloseable is null

How does the try-with feature work for AutoCloseable variables that have been declared null ? try-with功能如何用于已声明为null AutoCloseable变量?

I assumed this would lead to a null pointer exception when it attempts to invoke close on the variable, but it runs no problem: 我假设当它尝试调用变量上的close时会导致空指针异常,但它运行没有问题:

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

The Java Language Specification specifies that it is closed only if non-null, in section 14.20.3. Java语言规范指定仅在非空时关闭它,在14.20.3节中 try-with-resources : 尝试资源

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. 如果引用为非null,则远程记录器代理将关闭,正如我们所期望的那样。 But if the reference is null, no attempt is made to call close() on it, no NullPointerException is thrown, and the code still works. 但是如果引用为null,则不会尝试对其调用close(),不会抛出NullPointerException,代码仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM