gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:02:51 25 4
gpt4 key购买 nike

请看下面的代码:

Method methodInfo = MyClass.class.getMethod("myMethod");

这可行,但方法名称作为字符串传递,因此即使 myMethod 不存在也会编译。

另一方面,Java 8 引入了方法引用功能。它在编译时检查。可以使用此功能获取方法信息吗?

printMethodName(MyClass::myMethod);

完整示例:

@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 is somehow possible to
// obtain java.lang.reflect.Method for myMethod inside printMethodName?
printMethodName(MyClass::myMethod);
}

换句话说,我想要一个等效于以下 C# 代码的代码:

    private static class InnerClass
{
public static void MyMethod()
{
Console.WriteLine("Hello");
}
}

static void PrintMethodName(Action action)
{
// Can I get java.lang.reflect.Method in the same way?
MethodInfo methodInfo = action.GetMethodInfo();
}

static void Main()
{
PrintMethodName(InnerClass.MyMethod);
}

最佳答案

不,没有可靠、受支持的方法来执行此操作。您将方法引用分配给功能接口(interface)的实例,但该实例是由 LambdaMetaFactory 构建的,并且无法深入到它以找到您最初绑定(bind)到的方法。

Java 中的 Lambda 表达式和方法引用与 C# 中的委托(delegate)有很大不同。有关一些有趣的背景,请阅读 invokedynamic

此处的其他答案和评论表明,目前可以通过一些额外的工作来检索绑定(bind)方法,但请确保您理解这些注意事项。

关于java - 如何获取 Java 8 方法引用的 MethodInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com