[英]explanation needed: ternary operator in java
有问题的行是return pFile.exists() ? true : null;
return pFile.exists() ? true : null;
。 因为它没有引起任何编译错误,对此有什么解释。 它最终提高了NPE
。
import java.io.File;
public class Main {
public static void main(String... args) {
boolean accept = accept(new File(""));
System.out.println("accept = " + accept);
}
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
return pFile.exists() ? true : null; //this line should throw compilation error
}
}
pFile
不为null
; 如您所见,实例化File
。 但显然文件不存在。 问题不在于pFile
。 我对运算符如何处理null
感兴趣。
你的代码相当于:
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
Boolean tmp = pFile.exists() ? true : null;
return (boolean) tmp;
}
换句话说,在这种情况下,条件运算符的类型是Boolean
,然后该值被取消装箱以返回boolean
。 取消装箱为null
,会出现异常。
从Java语言规范的15.25节 :
否则,第二和第三操作数分别是S1和S2类型。 设T1是将拳击转换应用于S1所产生的类型,让T2为应用到S2的装箱转换所产生的类型。 条件表达式的类型是将捕获转换(第5.1.10节)应用于lub(T1,T2)(第15.12.2.7节)的结果。
我相信这是适用的情况,虽然我会认为它不是那么清楚。
从函数返回Boolean null
定义为返回boolean
(基本类型;注意小b
)。 null
值自动取消装箱,并且会产生NPE。
实际上,正在使用空字符串来创建file
。 这会产生一个空的abstract pathname
,没有前缀(或目录)和空名称序列。 所以Windows无法创建file
。 这反过来又是一个NPE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.