0: new #7; //class debug/Test
3: dup
4: invokespecial #8; //Method "":()V
7: pop
8: return
}
如果在同一个类中,一个构造方法调用了另一个构造方法,那么对应的""方法就会调用另一个"",但是实例变量和初始化块会被忽略,否则它们就会被多次执行。
package debug;
public class Test {
String s1 = rt("s1");
String s2 = "s2";
public Test(){
s1 = "s1";
}
public Test(String s){
this();
if(1==1) throw new Runtime();
}
String rt(String s){
return s;
}
public static void main(String[] args) {
new Test("");
}
}
深入理解Java初始化的含义(4)
时间:2010-12-31
反编译的结果:
Compiled from "Test.java"
public class debug.Test extends java.lang.Object{
java.lang.String s1;
java.lang.String s2;
public debug.Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: aload_0
5: aload_0
6: ldc #2; //String s1
8: invokevirtual #3; //Method rt:(Ljava/lang/String;)Ljava/lang/String;
11: putfield #4; //Field s1:Ljava/lang/String;
14: aload_0
15: ldc #5; //String s2
17: putfield #6; //Field s2:Ljava/lang/String;
20: aload_0
21: ldc #2; //String s1
23: putfield #4; //Field s1:Ljava/lang/String;
26: return
public debug.Test(java.lang.String);
Code:
0: aload_0
1: invokespecial #7; //Method "":()V
4: new #8; //class java/lang/RuntimeException
7: dup
8: invokespecial #9; //Method java/lang/RuntimeException."":()V
11: athrow
java.lang.String rt(java.lang.String);
Code:
0: aload_1
1: areturn
public static void main(java.lang.String[]);
Code:
0: new #10; //class debug/Test
3: dup
4: ldc #11; //String
6: invokespecial #12; //Method "":(Ljava/lang/String;)V
9: pop
10: return
}
我们看到,由于Test(String s)调用了Test();所以"":(Ljava/lang/String;)V不再对实例变量和初始化块进次初始化:
public debug.Test(java.lang.String);
Code:
0: aload_0
1: invokespecial #7; //Method "":()V
4: new #8; //class java/lang/RuntimeException
7: dup
8: invokespecial #9; //Method java/lang/RuntimeException."":()V
11: athrow
而如果两个构造方法是相互独立的,则每个构造方法调用前都会执行实例变量和初始化块的调用:
package debug;
public class Test {
String s1 = rt("s1");
String s2 = "s2";
{
String s3 = "s3";
}
public Test() {
s1 = "s1";
}
public Test(String s) {
if (1 == 1)
throw new RuntimeException();
}
String rt(String s) {
return s;
}
public static void main(String[] args) {
new Test("");
}
}
深入理解Java初始化的含义(5)
时间:2010-12-31
反编译的结果:
Compiled from "Test.java"
public class debug.Test extends java.lang.Object{
java.lang.String s1;
java.lang.String s2;
public debug.Test();
Code:
0
|