相关疑难解决方法(0)

如何获取Java 8方法引用的MethodInfo?

请看下面的代码:

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)

java reflection lambda java-8

68
推荐指数
5
解决办法
2万
查看次数

标签 统计

java ×1

java-8 ×1

lambda ×1

reflection ×1