Tostring method that is easy to overlook

xiaoxiao2021-03-06  52

First look at a program / * * Created on 2005-2-24 * /

/ ** * @Author snowway * / public class a {

Private string id;

Public string toString () {returnid;

Public static void main (string [] args) {system.out.println (new a ());}}

It turns out that I think of it will print null, and the results are: 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)

After careful debug, you know that the process is like this: first call the printStream.Println (Object) method, PrintLn (Object) calls the PrintStream.Print (Object) method, this method uses String.Valueof (Object) to get the target string output , Let's take a look at String.Valueof (Object Obj) Source: Public Static String Valueof (Object Obj) {RETURN (OBJ == NULL)? "Null": obj.tostring ();} There is no problem, because we pass New a ()! = null, call new a (). toString (), then TOSTRING returns this.id, it is obviously null, and finally PrintLn call Write (Str, 0, str.length ()); Oh, the problem came out, str == null, then str.length obviously wants to throw NPE.

The lesson given to me is: Don't let the class TOSTRING method returns NULL!

转载请注明原文地址:https://www.9cbs.com/read-54150.html

New Post(0)