Hi,

as far as I can see, the code should not even compile, as there's a static field in Test_1 which is initialized with an expression that throws checked exceptions (findStatic(..)).

In addition, it seems to me that there's nothing in your code that reveals whether Test_2 has been initialized during the lookup. How can you tell?

Finally, the method handle invocation in Test_1 will throw, as you don't pass any argument to a handle that expects one.

Can you perhaps add more details?


Greetings
Raffaello



On 2022-03-17 17:42, Cheng Jin wrote:
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

Reply via email to