(转 from snowway's blog )
先看一段程序
/*
* Created on 2005-2-24
*/
/**
* @author snowway
*/
public class A{
private String id;
public String toString(){
return this.id;
}
public static void main(String[] args){
System.out.println(new A());
}
}
原来我想当然以为会打印null,可运行结果是:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:126)
at java.io.PrintStream.write(PrintStream.java:457)
at java.io.PrintStream.print(PrintStream.java:616)
at java.io.PrintStream.println(PrintStream.java:753)
at A.main(A.java:17)
仔细debug后才知道流程是这样的:
首先调用PrintStream.println(Object)方法,println(Object)调用PrintStream.print(Object)方法,这个方法使用了String.valueOf(Object)来
获取对象的字符串输出,我们看看String.valueOf(Object obj)源码:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
没有问题,由于我们传递的new A()!=null,所以调用new A().toString(),那么此时toString返回的是this.id,很显然是null,
最后println调用了write(str, 0, str.length() ); 呵呵,问题出来了,str==null,那么str.length显然是要抛出NPE的。
给我的教训是:千万不要让类的toString方法返回null!