将方法调用转换为该方法的 java.lang.reflect.Method 对象

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

我正在努力尝试将 'method call' 转换为该方法的 'method object'。

我有:

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'
     }
 });

我知道我可以用 lambda 简化它,但我认为这会让我想做的事情更加清楚。

p.getAge() 目前 return 是 'int',但我希望它是 return 'Method object' 的 'getAge()'。 'Method object' 的意思是:

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

这样做的原因是,我正在构建自己的小框架以获取经验并让用户使用:

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

似乎对用户更友好。

注意:我有自己的 'Function' 接口,它不将 'Method' 作为第二个通用类型,因此用户只需键入:

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

又找了几天终于找到了答案,在一个旧的堆栈溢出问题的评论中,我找到了这个link:


这个答案来自另一个问题 links 到由 'Benji Weber' 编写的库,该库使用 'cglib' 创建代理对象以获取 Function 的方法.

含义:

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