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

Remi Forax forax at univ-mlv.fr
Thu Mar 17 17:36:47 UTC 2022


----- Original Message -----
> From: "Cheng Jin" <jincheng at ca.ibm.com>
> To: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Sent: Thursday, March 17, 2022 5:42:57 PM
> Subject: When to initialize the method's class for MethodHandles.Lookup.findStatic()?

> 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().

Hi,
if by initialization you mean running the static block, then it's a bug.

As far as i remember, the JVMS spec cleanly separate the Linking exceptions from the Runtime exceptions.
https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-6.html#jvms-6.5.invokestatic

The linking exceptions occurs when calling findStatic() while the runtime exceptions will appear at runtime when calling invokeExact()/invoke().

> 
> Best Regards
> Cheng Jin

regards,
RĂ©mi


More information about the core-libs-dev mailing list