当 AutoCloseable 为 null 时尝试使用资源
Try-With Resource when AutoCloseable is null
try-with 功能如何用于已声明 null
的 AutoCloseable
变量?
我假设这会在它尝试调用变量时导致空指针异常 close
,但它运行没有问题:
try (BufferedReader br = null){
System.out.println("Test");
}
catch (IOException e){
e.printStackTrace();
}
Java 语言规范在 14.20.3. try-with-resources:
部分指定仅当非空时才关闭
A resource is closed only if it initialized to a non-null value.
当资源有时出现而其他资源不出现时,这实际上很有用。
例如,假设您可能有也可能没有某个远程日志系统的可关闭代理。
try ( IRemoteLogger remoteLogger = getRemoteLoggerMaybe() ) {
if ( null != remoteLogger ) {
...
}
}
如果引用不为空,则远程记录器代理将关闭,如我们所料。但如果引用为 null,则不会尝试对其调用 close(),不会抛出 NullPointerException,代码仍然有效。
try-with 功能如何用于已声明 null
的 AutoCloseable
变量?
我假设这会在它尝试调用变量时导致空指针异常 close
,但它运行没有问题:
try (BufferedReader br = null){
System.out.println("Test");
}
catch (IOException e){
e.printStackTrace();
}
Java 语言规范在 14.20.3. try-with-resources:
部分指定仅当非空时才关闭A resource is closed only if it initialized to a non-null value.
当资源有时出现而其他资源不出现时,这实际上很有用。
例如,假设您可能有也可能没有某个远程日志系统的可关闭代理。
try ( IRemoteLogger remoteLogger = getRemoteLoggerMaybe() ) {
if ( null != remoteLogger ) {
...
}
}
如果引用不为空,则远程记录器代理将关闭,如我们所料。但如果引用为 null,则不会尝试对其调用 close(),不会抛出 NullPointerException,代码仍然有效。