介绍
几分钟我就陷入了这个问题.因此,它可能会帮助其他人,这是一个有趣的错误.但是解决第一个问题使我想到了另一个问题.
第一个难题:
考虑以下代码:
public void setValue(ValueWrapper valueWrapper) {
if (anotherValueWrapper == null) {
anotherValueWrapper = new AnotherValueWrapper();
}
anotherValueWrapper.setValue(valueWrapper == null ? null : valueWrapper.getValue());
}
事实 :
>此代码编译
> getter和setter是标准的(除了返回字段或设置字段外,没有其他代码)
问题
在执行过程中,有一种情况是代码失败并返回空指针异常.
第一个难题是:什么时候该代码可以导致NullPointerException?
不要看第二个问题,因为如果您没有找到第一个问题,那就太麻烦了.
第二个问题
好的,您找到了(或可能没有找到):问题是当AnotherValueWrapper像这样编写时:
public class AnotherValueWrapper {
private long value;
public long getValue() { return value; }
public void setValue(long value) { this.value = value; }
}
和ValueWrapper:
public class ValueWrapper {
private Long value;
public Long getValue() { return value; }
public void setValue(Long value) { this.value = value; }
}
这是第二个问题:
如果我写:
anotherValueWrapper.setValue(null);
要么
anotherValueWrapper.setValue(valueWrapper == null ? "test": valueWrapper.getValue());
如果由于anotherValueWrapper.setValue采用一个原语(long)而不是Long(object)的事实而无法编译.
但是这段代码会编译:
anotherValueWrapper.setValue(valueWrapper == null ? null : valueWrapper.getValue());
为什么呢