通过类访问器获取直接Java方法



是否有办法通过直接访问获得java.lang.reflect.Method对象?如下面示例中的MyUtils::sum:

class MyUtils {
static int sum(int a, int b) {
return a + b;
}
}
java.lang.reflect.Method myUtilsSumMethod = MyUtils::sum;
int sum = myUtilsSumMethod.invoke(null, 2, 3); // should be 5

或者我总是必须使用反射API的字符串名称?

MyUtils.class.getDeclaredMethod("sum", Integer.class, Integer.class)

因为只要我重构了方法的名称,我就会在运行时得到一个异常,我希望在编译时已经有错误了。

这里不需要反射-MyUtils::sum返回可以存储在IntBinaryOperator中的方法引用:

IntBinaryOperator myUtilsSumMethod = MyUtils::sum;
int sum = myUtilsSumMethod.applyAsInt(2, 3); // should be 5

最新更新