AutoCloseable 为空时的试用资源 [英] Try-With Resource when AutoCloseable is null

查看:24
本文介绍了AutoCloseable 为空时的试用资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try-with 功能如何对已声明为 nullAutoCloseable 变量起作用?

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

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

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

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

推荐答案

Java 语言规范在 14.20.3.尝试资源:

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

资源只有在初始化为非空值时才会关闭.

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

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

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

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

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

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

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.

这篇关于AutoCloseable 为空时的试用资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆