简体   繁体   中英

Java 8 expression evaluation sequence

I have a case like

MyClass.invoke( anObject.setSystem() );

Is there a guarantee that anObject.setSystem() will be called before MyClass is loaded? As the initialization code of MyClass depends on the result of anObject.setSystem() .

It is running with Java 8. Any suggestions/hints would be appreciated. Many thanks

MyClass will be loaded and all of its static fields and static initializers will be initialized before MyClass.invoke() is called.

See JLS 12.14.1

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked. <------------ right here
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

  • EDIT Thanks to @Holger and @gigi's comments, there was still the question as to whether the invocation that triggers the loading of the class occurs before or after the evaluation of the argument expression passed into it. I think the answer to that is in JLS 15.12.4 , which states,

    At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

    The evaluation of argument expressions (step 2) occurs before the code to execute the method is located, (step 4, which probably results in the class being loaded and statically initialized) and only then, in the final step, is the static method invoked.

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM