什么是空指针异常(java.lang.NullPointerException
)以及它的产生原因?
有哪些方法/工具可以用来确定它的原因,以便防止该异常导致程序过早终止?
什么是空指针异常(java.lang.NullPointerException
)以及它的产生原因?
有哪些方法/工具可以用来确定它的原因,以便防止该异常导致程序过早终止?
this
引用。看下面这个例子:public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
另外在你的代码中的另一个位置:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
这是一个重要的知识点 - 当没有任何引用指向一个对象时(在上面的例子中,当 reference
和 otherReference
都指向 null 时),那么该对象就变得 "不可达"。我们无法再使用它,因此该对象已准备好被垃圾回收,虚拟机将释放该对象使用的内存,并分配另一个对象。
当一个人声明一个对象数组,然后立即尝试对其中的元素进行解引用时,会发生NullPointerException
的另一个发生。
String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
如果将比较顺序颠倒,即在保证非空对象的情况下使用.equals
,则可以避免此特定的NPE。
数组中的所有元素都会被初始化为其共同的初始值;对于任何类型的对象数组,这意味着所有元素都是null
。
在访问或解除引用数组元素之前,必须先对数组元素进行初始化。
String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
Optional
之前的一种模式是返回null
。这个关键字很好用。知道如何防范它非常重要。 这里提供了其中一个常见情况以及缓解措施。 - Makoto