null
传递给无法接受它们的方法:private void someMethod(SomeType pointer, SomeType anotherPointer) {
Objects.requireNonNull(pointer, "pointer cannot be null!");
Objects.requireNonNull(anotherPointer, "anotherPointer cannot be null!");
// Rest of method
}
我认为这种方法可以让代码变得整洁易读,我正在努力鼓励同事们使用它。但是有一个(尤其是知识渊博的)同事持反对态度,并表示旧方法更有效:
private void someMethod(SomeType pointer, SomeType anotherPointer) {
if (pointer == null) {
throw new NullPointerException("pointer cannot be null!");
}
if (anotherPointer == null) {
throw new NullPointerException("anotherPointer cannot be null!");
}
// Rest of method
}
他说调用requireNonNull
会在JVM调用栈上放置另一个方法,并且会导致性能比简单的== null
检查差。那么我的问题是:是否有任何证据表明使用Objects.requireNonNull
方法会导致性能损失?
public Object self() { return this; }
会更美观。不是吗? - Jaumzera