今天我在写测试的时候遇到了一个奇怪的情况。基本上,我上了一堂有数据的课。以 Toy 为例,我们可以从中检索名称:
public class Toy {
private String name;
public Toy(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
我有一个异常(exception),它的工作方式与此类似(例如,只显示我们在它变坏之前处理的所有对象的数据);我还包括一个主要用于测试目的:
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 block 中所写,异常应该在 ToyFactoryException 中被捕获。
但是,在异常情况下,它会尝试在此处读取 firstToy.getName():firstToy != null ? firstToy.getName() : 空
firstToy != null
应该评估为 false,这意味着它不应该首先尝试调用 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
读取为 true。
如果您改用这种方式编写 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)
关于Java 三元运算符严重评估 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55386008/