17

我有以下这段代码:

public abstract class UCMService{
    private String service;     

    protected DataMap dataMap = new DataMap(); 

    protected class DataMap extends HashMap<String,String> {

        private static final long serialVersionUID = 4014308857539190977L;

        public DataMap(){
            System.out.println("11111");
            put("IdcService",service);
        }
    }

    public UCMService(String service){
        System.out.println("2222");
        this.service = service;
    }
}

现在在控制台中System.out.printlnDataMap构造函数的构造函数在构造函数之前执行UCMService

我想知道为什么会这样。

4

2 回答 2

37

这是因为在编译时,编译器会将您在声明位置所做的每个初始化都移动到类的每个构造函数中。所以UCMService类的构造函数被有效地编译为:

public UCMService(String service){
    super();  // First compiler adds a super() to chain to super class constructor
    dataMap = new DataMap();   // Compiler moves the initialization here (right after `super()`)
    System.out.println("2222");
    this.service = service;
}

所以,很明显DataMap()构造函数是在类的print语句之前执行的UCMService。同样,如果您的UCMService类中有更多构造函数,则初始化将移至所有构造函数。


我们来看一个简单类的字节码:

class Demo {
    private String str = "rohit";

    Demo() {
        System.out.println("Hello");
    }
}

编译这个类,并执行命令 - javap -c Demo。您将看到以下构造函数的字节码:

Demo();
    Code:
       0: aload_0
       1: invokespecial #1   // Method java/lang/Object."<init>":()V
       4: aload_0
       5: ldc           #2   // String rohit
       7: putfield      #3   // Field str:Ljava/lang/String;
      10: getstatic     #4   // Field java/lang/System.out:Ljava/io/PrintStream;
      13: ldc           #5   // String Hello
      15: invokevirtual #6   // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      18: return

您可以在第 7 行看到putfield指令,将字段初始化str"rohit",它位于print语句之前(第 7 行的指令15

于 2013-09-16T14:16:40.813 回答
13

简短的回答
因为规范是这样说的。

长答案
构造函数无法使用内联初始化的字段会很奇怪。

你希望能够写作

SomeService myService = new SomeService();
public MyConstructor() {
    someService.doSomething();
}
于 2013-09-16T14:10:49.563 回答