可选的三元运算符中不需要的空指针异常
Unwanted Null Pointer Exception in ternary operator with Optional
根据我的理解,以下代码不应抛出 Null Pointer exception
,因为我正在安全地使用可选接口。
但是,当我 运行 这段代码时它抛出 NPE
。
public class Test {
public static void main(String[] args) {
final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
}
}
如果我的代码某处有误,请告诉我并帮助我改正。
你肯定会得到一个 NullPointerException,因为你的右手边只是一种非常冗长的表达 null
的方式。您将 null
包装在 Optional
中,从而强制 orElse
执行到 null
.
在解析为 int
的语句中包含 null
,正如@Hoopje 所解释的(即使它已分配给 Integer
变量)导致 NullPointerException
.
只需将 null
包裹在 Optional
中,再次展开时仍会得到 null
。
我找到解决方法
final Integer inte = false ? (Integer)0 : Optional.<Integer>ofNullable(null).orElse(null);
或
final Integer inte = false ? (Integer)0 : Optional.ofNullable((Integer)null).orElse(null);
三元运算符返回的类型应为 int(因为字面量为 0)。
你得到 NullPointerException 的原因是表达式 false ? 0 : Optional.ofNullable((Integer) null).orElse(null)
的类型是 int
(根据 JLS Table 15.25-C)。
表达式 Optional.ofNullable((Integer) null).orElse(null)
的计算结果为 null
,将 null
转换为 int
会导致 NullPointerException。
根据我的理解,以下代码不应抛出 Null Pointer exception
,因为我正在安全地使用可选接口。
但是,当我 运行 这段代码时它抛出 NPE
。
public class Test {
public static void main(String[] args) {
final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
}
}
如果我的代码某处有误,请告诉我并帮助我改正。
你肯定会得到一个 NullPointerException,因为你的右手边只是一种非常冗长的表达 null
的方式。您将 null
包装在 Optional
中,从而强制 orElse
执行到 null
.
在解析为 int
的语句中包含 null
,正如@Hoopje 所解释的(即使它已分配给 Integer
变量)导致 NullPointerException
.
只需将 null
包裹在 Optional
中,再次展开时仍会得到 null
。
我找到解决方法
final Integer inte = false ? (Integer)0 : Optional.<Integer>ofNullable(null).orElse(null);
或
final Integer inte = false ? (Integer)0 : Optional.ofNullable((Integer)null).orElse(null);
三元运算符返回的类型应为 int(因为字面量为 0)。
你得到 NullPointerException 的原因是表达式 false ? 0 : Optional.ofNullable((Integer) null).orElse(null)
的类型是 int
(根据 JLS Table 15.25-C)。
表达式 Optional.ofNullable((Integer) null).orElse(null)
的计算结果为 null
,将 null
转换为 int
会导致 NullPointerException。