[英]Try-with-resources using conditional expression
Intellij IDEA 14看到以下代碼時,警告我“ PrintStream不帶try-with-resources使用”:
public static void main(String[] args) throws IOException {
try (PrintStream out = args.length > 0 ? new PrintStream(args[0]) : null) {
if (out != null)
out.println("Hello, world!");
}
}
使用javap -c
可以看到,在try塊末尾資源已按預期關閉。
如上所述,僅當在條件表達式中創建資源時才發出警告。 以典型方式完成時不會發出。
這是一個IDEA錯誤還是有道理?
我認為IDEA對此感到困惑。 對我來說,這似乎是一種有效的try-with-resources
。 JLS§14.20.3將語句的“ 資源”部分顯示為:
資源:
{VariableModifier} UnannType VariableDeclaratorId = 表達式
...並且似乎沒有對Expression施加限制。 因此,我看不出為什么可能會產生null
的表達式會使它以某種方式無效,以及§14.20.3.1中翻譯的“簡單”示例:
{
final {VariableModifierNoFinal} R Identifier = Expression;
Throwable #primaryExc = null;
try ResourceSpecification_tail
Block
catch (Throwable #t) {
#primaryExc = #t;
throw #t;
} finally {
if (Identifier != null) {
if (#primaryExc != null) {
try {
Identifier.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
Identifier.close();
}
}
}
}
...就可以了。
您的代碼原則上沒有問題,因此可以忽略IntelliJ給出的警告。
但是,如果您這樣編寫代碼,則代碼將更加清晰:
public static void main(String[] args) throws IOException {
if (args.length > 0) {
try (PrintStream out = new PrintStream(args[0])) {
out.println("Hello, world!");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.