1

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());
Niels
  • 306
  • 2
  • 11
  • Indeed I need the getAge to return itself, this is because, getAge represents a Getter method for the property 'age', and via the method object I want to get the property 'age'. – Niels Jan 14 '22 at 12:43
  • I don't want to execute the method, when I have the method I will get the property 'private int age' of that method. (if the passed method is a getter-method). – Niels Jan 14 '22 at 12:50
  • method.getName() will return a String 'getAge'. The framework will rely on correctly specifying the naming conventions of getter method (name of the property with 'get' prefix or 'is' prefix for booleans) and thus I can extract 'age' from 'getAge' and use java reflections to get the property 'age' – Niels Jan 14 '22 at 12:54
  • Yes the reason I want to do it this was, Fleunt API for Entity Framework (C#) uses a similar approach for explicitly specifying relations between entities (classes). and I just want to recreate that approach and I have been trying to do so for the past few days but I haven't succeeded. Therefore my question here – Niels Jan 14 '22 at 13:03

1 Answers1

0

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'.
Niels
  • 306
  • 2
  • 11