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());
4
  • 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'. Commented Jan 14, 2022 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). Commented Jan 14, 2022 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' Commented Jan 14, 2022 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 Commented Jan 14, 2022 at 13:03

1 Answer 1

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 answer from another question which 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'.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.