Express a generic `MethodType` with the return type like any object

Let there be a class in my task:

class MyClass {
    String name() {
        return toString();
    }
}

I want to create an instance MethodTypethat describes a return method, which is "any" object. I am trying to do the following:

MethodType genericTypeWithObjectReturn = 
    MethodType.methodType(Object.class, new Class[] {});

then try to find the 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 type of the return method must be exactly the same type; namely, I should have used String.classin the above description to determine MethodType. It's right? Is there a way that I can do this the way I described, and prefer not to use the reflection API?

+4
3

- ...

Type . , MethodHandles-API, , , - . , , MethodHandles # unreflect * .

+2

find{Virtual,Static} , . JVM, , Java . Class.getMethod ( ):

C: C , . C , , , , ; .

, , , Java , , Java . . , ; , .

, JVM Class.getMethod , ( ) . , JVM, , , JVM, , , . ( pow(int, int) , int, long BigInteger, foo(pow(1000, 100000));.)

, , API , , , .


Class.getMethod, MethodHandles.Lookup.unreflect .

0

Yes. you must use String.class to resolve the correct type of method. since I know that you cannot implement it using api methods, but you can use the Reflection API.

0
source

Source: https://habr.com/ru/post/1523721/


All Articles