java - Java 三元运算符错误地评估 null
问题描述
今天我在写测试时遇到了一个奇怪的情况。基本上,我有一个数据类。以 Toy 为例,我们可以从中检索名称:
public class Toy {
private String name;
public Toy(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
我有一个例外,它的工作方式与此类似(例如,在它变坏之前只显示我们正在处理的所有对象的数据);我还包括一个主要用于测试目的:
public class ToyFactoryException extends Exception {
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? firstToy.getName() : null +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
public static void main(String[] args) {
try {
throw new ToyFactoryException(null, new Toy("hi"));
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
}
正如我在第一个 catch 块中所写,异常应该在 ToyFactoryException 中被捕获。
但是,在例外情况下,它试图在这里读取 firstToy.getName() :firstToy != null ? firstToy.getName() : null
firstToy != null
应该评估为假,这意味着它不应该首先尝试调用firstToy.getName()
。当您以相反的顺序编写它时:
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? null : firstToy.getName() +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
你意识到它null
现在改为阅读,这意味着它真的阅读firstToy != null
为真的。
如果你改用这种方式编写 main (null 是构造函数的第二个参数):
public static void main(String[] args) {
try {
throw new ToyFactoryException(new Toy("hi"), null);
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
尽管 secondToy 三元条件的编写方式与 firstToy 三元相同,但它工作正常。
为什么 firstToy 上的三元条件不能正确评估 null?
解决方案
您应该在条件表达式周围加上括号。
这个:
"string " + firstToy != null ? firstToy.getName() : null
这意味着:
("string " + firstToy) != null ? firstToy.getName() : null
你需要这个:
"string " + (firstToy != null ? firstToy.getName() : null)
推荐阅读
- javascript - 文件中的 Laravel javascript 不起作用,但如果通过 CDN 包含则可以
- python - 如何使用Python替换文本文件中特定位置的单词
- r - 创建结果表并绘制直方图
- excel - 如果组合框为空,则显示/隐藏文本框
- vim - 用于对齐逗号分隔参数函数的 Vim 表格/正则表达式
- rust - 如何在条件下进行范围反转?
- javascript - Firestore onSnapshot() 方法触发多次
- delphi - 如何从剪贴板中选择特定行
- android - Android singleTask 活动后台问题
- javascript - Dialogflow - Google Assistant - 最多支持两个“simple_responses”