Java 引用枚举实例时发生StackOverflowerError错误

Java 引用枚举实例时发生StackOverflowerError错误,java,enums,Java,Enums,我想知道为什么这样做时会得到java.lang.StackOverflowerError enum Grade { A, B, C, D, F, INCOMPLETE; public String toString() { System.out.println(this); //<-- error here return "Name of enum: "+this.name()+"\n"+"Ordinal of enum: "+this.

我想知道为什么这样做时会得到java.lang.StackOverflowerError

enum Grade { 
    A, B, C, D, F, INCOMPLETE;

    public String toString() {
        System.out.println(this); //<-- error here
        return "Name of enum: "+this.name()+"\n"+"Ordinal of enum: "+this.ordinal();
    }
};

这很容易。您可以递归地调用toString,而不需要递归结束

public String toString() {
    System.out.println(this); //<-- this will execute toString() again
}

如果您将某个对象作为参数传递,其中需要字符串,java将在内部调用其toString方法。

代码段中的以下行:

System.out.println(this);
内部通话

public void println(Object x) {
    String s = String.valueOf(x); <---
    synchronized (this) {
        print(s);
        newLine();
    }
}
定义为:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString(); <--- leads to recursive call
}

因此导致StackOverflowerError

通过out.printlnObjects无限自递归非静态toString与其他任何对象一样,打印调用它的toString