简体   繁体   中英

Converting method call to the java.lang.reflect.Method object of that method

I am struggling trying to convert a 'method call' to the 'method object' of that method.

I have:

someClassInstance.someInstanceMethod(new Function<Person, Method>() {
     @Override
     public Method apply(Person p) {
         return p.getAge(); // I want to convert 'p.getAge()' to the the method of 'getAge'
     }
 });

I know I can simplify this with lambda's but I thought this would make what I want to do more clear.

p.getAge() currently returns an 'int', but I want it to return the 'Method object' of 'getAge()'. What I Mean by the 'Method object' is this:

 Method method = Person.class.getMethod("getAge"); // I basically want to return this.

The reason for this is, I'm building my own little framework to gain experience and letting the user use:

someClassInstance.someInstanceObject((Function<Person, Method>) o -> o.getAge());

Seems more user friendly.

NOTE: I do have my own interface of 'Function' that does not take 'Method' as a second generic type so the user only has to type:

someClassInstance.<Person>someInstanceMethod(o -> o.getAge());

After searching for some more days I finally found an answer, somewhere in the comments of an old stack overflow question, I found this link:

https://stackoverflow.com/a/22745127/3478229

This answer from another question links to a library written by 'Benji Weber' this library used 'cglib' to create proxy objects to get the method of a Function<T, U>.

Meaning:

 someMethod(Person::getAge) //returns a String 'age'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM