When to initialize the method's class for MethodHandles.Lookup.findStatic()?

Cheng Jin jincheng at ca.ibm.com
Thu Mar 17 16:42:57 UTC 2022


Hi there,

The document of  https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/invoke/MethodHandles.Lookup.html#findStatic(java.lang.Class,java.lang.String,java.lang.invoke.MethodType) in the Java API is ambiguous in terms of when to initialize the method's class as follows (the same description as in other OpenJDK versions)

If the returned method handle is invoked, the method's class will be initialized, if it has not already been initialized.


It occurs to me that the method's class should be initialized when invoking the method handle but OpenJDK actually chooses to do the initialization in lookup.findStatic() rather than in mh.invoke()
e.g.
import java.lang.invoke.*;

public class Test_1 {
    static MethodHandle mh = MethodHandles.lookup().findStatic(Test_2.class, "testMethod", MethodType.methodType(int.class, int.class)); <----------- Test_2.class gets initialized and verified.

    public static void main(String[] args) throws Throwable {
        Test_1.mh.invoke();
    }
}

public class Test_2 {
    static int testMethod(int value) { return (value + 1); }
}

So there should be more clear explanation what is the correct or expected behaviour at this point and why OpenJDK doesn't comply with the document to delay the initialization of the method's class to mh.invoke().

Best Regards
Cheng Jin


More information about the core-libs-dev mailing list