需要解释:java中的三元运算符
有问题的行是 return pFile.exists() ? true:空;。由于它不会引发任何编译错误,对此有何解释。它最终筹集了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
感兴趣。
The line in question is return pFile.exists() ? true : null;
. As it does not raise any compilation error, what is the explanation for this. It ended up raising 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
is not null
; a File
is instantiated as you can see. But obviously the file is not there. The question is not about pFile
. I am interested in how the operator is dealing with null
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码等效于:
换句话说,条件运算符的类型在这种情况下为
boolean
,然后将其拆箱以返回boolean
。当null
被拆箱时,您会得到异常。来自第15.25节 Java语言规范的第15.25节
我相信在这里适用的情况,尽管我会授予的那样清楚。
You code is equivalent to:
On other words, the type of the conditional operator is
Boolean
in this case, and then the value is being unboxed to return aboolean
. Whennull
is unboxed, you get an exception.From section 15.25 of the Java Language Specification:
I believe that's the case that's applicable here, although I'll grant it's not as clear as it might be.
您从定义为返回的
boolean
(原始类型;注意小b
)的函数中返回boolean null
。null
值将自动卸载,并置于NPE。You return
Boolean null
from function defined as returningboolean
(a primitive type; note smallb
). Thenull
value is automatically unboxed, and casues NPE.实际上,正在使用空字符串来创建
文件
。这将导致一个空的抽象路径名
没有前缀(或目录)和一个空名称序列。因此Windows无法创建文件
。反过来,这是扔npe
Actually, an empty string is being used to create a
file
. This results in a emptyabstract pathname
with no prefix(or directory) and an empty name sequence. So windows is unable to create afile
. This in turn is throwing aNPE