JAVA基础
public class Reluctant {
private Reluctant instance = new Reluctant();
public Reluctant() throws Exception {
throw new Exception("-->Reluctant Exception");
}
public static void main(String[] args) {
try {
Reluctant r = new Reluctant(); //调用构造方法之后,为啥初始化instance?
System.out.println("-->main");
} catch (Exception e) {
System.out.println("-->main Exception");
}
}
}
我DEBUG了下,发现在构造方法和instance对象初始化之间,是死循环。
1.对象的初始化顺序?
2.为什么这里产生了递归调用?
请大家讲下,谢谢!
------解决方案--------------------Compiled from "TRRRR.java"
public class test.TRRRR extends java.lang.Object{
public test.TRRRR() throws
java.lang.Exception;
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: new #2; //class test/TRRRR
8: dup
9: invokespecial #3; //Method "<init>":()V
12: putfield #4; //Field instance:Ltest/TRRRR;
15: new #5; //class java/lang/Exception
18: dup
19: ldc #6; //String -->Reluctant Exception
21: invokespecial #7; //Method java/lang/Exception."<init>":(Ljava/lang/St
ring;)V
24: athrow
循环引用构造 看标号5