You can’t get a java.lang.reflection.Method
with ldc
. Doing an ldc
to a CONSTANT_MethodHandle
produces a MethodHandle
.
These method handles can be used to execute the associated code (despite its name, it is not restricted to methods) and you can query its parameter types. But you cannot convert it into a Reflection Method
. Though you can do the inverse, convert a java.lang.reflection.Method
into a java.lang.invoke.MethodHandle
.
Since java.lang.invoke.MethodHandle
can invoke methods far faster and without the overhead of autoboxing and without putting all arguments into an array, you might wan’t to work with it anyway.
By the way, using reflection with primitive types is quite easy, e.g.
obj.getClass()
.getDeclareMethodMethod("foo", int.class, String.class)
.invoke(obj, 42, "blah");
It will wrap the int
into an Integer
and create a temporary Object[]
array holding both argument Object
s. But for the lookup of the method you have to specify the right primitive type.
Starting with Java 8, there is a way to convert a direct MethodHandle
to a Method
, so you could use an ldc
instruction followed by a conversion, but you need to acquire a MethodHandles.Lookup
instance and use it two times, so the byte code would look like this:
ldc class java/lang/reflect/Method
ldc method handle <your desired method>
invokestatic java/lang/invoke/MethodHandles.reflectAs:(Ljava/lang/Class;Ljava/lang/invoke/MethodHandle;)Ljava/lang/reflect/Member;
checkcast java/lang/reflect/Method
which is slightly shorter than, e.g.
ldc class <declaring class of your desired method>
ldc string <name of your desired method>
ldc method type <type signature of your desired method>
invokevirtual java/lang/invoke/MethodType.parameterArray:()[Ljava/lang/Class;
invokevirtual java/lang/Class.getDeclaredMethod:(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;
keep in mind that on the bytecode level, there is no enforcement of exception handling