[英]Calling a Non-Static Method in a Null Object JAVA?
**public void testCompareTo() {
System.out.println("compareTo");
Patient p = null;
Patient instance = null;
int expResult = 0;
int result = instance.compareTo(p);
assertEquals(expResult, result);
}**
Is there a way to call a method in a null object or do I have to do an Exception here? 有没有一种方法可以在空对象中调用方法,或者我必须在这里做一个异常?
No, you can't call a non-static method on a null object, since that would cause a NullPointerException
. 不,您不能在null对象上调用非静态方法,因为那样会导致NullPointerException
。
You must verify that instance
is not null before calling instance.compareTo(p)
. 您必须在调用instance.compareTo(p)
之前确认instance
不为null。
null
objects by definition are... nothing. 根据定义, null
对象是……什么都没有。 You can't invoke an instance level method on a null object without causing a NullPointerException
. 您不能在没有引起NullPointerException
的情况下在空对象上调用实例级方法。
在这种情况下,NullPointerException是不可避免的,因为Java无法从null对象获取任何引用,这使得抛出NullPointerException很明显
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.