Let the following be a class in my problem:
class MyClass {
String name() {
return toString();
}
}
I want to create an instance of MethodType
which describes a method with a return that is "any" object. I am trying the following:
MethodType genericTypeWithObjectReturn =
MethodType.methodType(Object.class, new Class[] {});
then try to find a method using
MethodHandle mh =
lookup.findVirtual(MyClass.class, "name", genericTypeWithObjectReturn);
Using the above line, I get an exception:
Caused by: java.lang.NoSuchMethodError: MyClass.name()Ljava/lang/Object;
My observation is that the method return type should be exactly the same type; namely I should have used String.class
in the above statement to define MethodType
. Is this correct? Is there a way so that I can do this in the way I described and preferrably not using reflection API?
yes. you should use String.class for resolving right method type. as i know you can't implement it with method handles api, but you can use Reflection API.