When is an interface with a default method initialized?

前端 未结 4 1777
失恋的感觉
失恋的感觉 2020-11-30 18:18

While searching through the Java Language Specification to answer this question, I learned that

Before a class is initialized, its direct superclass m

4条回答
  •  猫巷女王i
    2020-11-30 18:35

    The instanceKlass.cpp file from the OpenJDK contains the initialization method InstanceKlass::initialize_impl that corresponds to the Detailed Initialization Procedure in the JLS, which is analogously found in the Initialization section in the JVM Spec.

    It contains a new step that is not mentioned in the JLS and not in the JVM book that is referred to in the code:

    // refer to the JVM book page 47 for description of steps
    ...
    
    if (this_oop->has_default_methods()) {
      // Step 7.5: initialize any interfaces which have default methods
      for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
        Klass* iface = this_oop->local_interfaces()->at(i);
        InstanceKlass* ik = InstanceKlass::cast(iface);
        if (ik->has_default_methods() && ik->should_be_initialized()) {
          ik->initialize(THREAD);
        ....
        }
      }
    }
    

    So this initialization has been implemented explicitly as a new Step 7.5. This indicates that this implementation followed some specification, but it seems that the written specification on the website has not been updated accordingly.

    EDIT: As a reference, the commit (from October 2012!) where the respective step has been included in the implementation: http://hg.openjdk.java.net/jdk8/build/hotspot/rev/4735d2c84362

    EDIT2: Coincidentally, I found this Document about default methods in hotspot which contains an interesting side note at the end:

    3.7 Miscellaneous

    Because interfaces now have bytecode in them, we must initialize them at the time that an implementing class is initialized.

提交回复
热议问题