请看下面的代码:
Method methodInfo = MyClass.class.getMethod("myMethod");
Run Code Online (Sandbox Code Playgroud)
这可行,但方法名称作为字符串传递,因此即使myMethod不存在,这也将编译.
另一方面,Java 8引入了方法引用功能.它在编译时检查.可以使用此功能获取方法信息吗?
printMethodName(MyClass::myMethod);
Run Code Online (Sandbox Code Playgroud)
完整示例:
@FunctionalInterface
private interface Action {
void invoke();
}
private static class MyClass {
public static void myMethod() {
}
}
private static void printMethodName(Action action) {
}
public static void main(String[] args) throws NoSuchMethodException {
// This works, but method name is passed as a string, so this will compile
// even if myMethod does not exist
Method methodInfo = MyClass.class.getMethod("myMethod");
// Here we pass reference to a method. It …Run Code Online (Sandbox Code Playgroud)