如何获取 Java 8 方法引用的 MethodInfo? [英] How to get the MethodInfo of a Java 8 method reference?
问题描述
请看下面的代码:
Method methodInfo = MyClass.class.getMethod("myMethod");
这可行,但方法名称作为字符串传递,因此即使 myMethod 不存在也会编译.
This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.
另一方面,Java 8 引入了方法引用特性.它在编译时检查.可以使用此功能获取方法信息吗?
On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?
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# 代码等效的代码:
In other words I would like to have a code which is the equivalent of the following C# code:
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);
}
推荐答案
不,没有可靠的、受支持的方法来做到这一点.您将方法引用分配给函数式接口的实例,但该实例是由 LambdaMetaFactory
制作的,并且无法深入其中以找到您最初绑定的方法.
No, there is no reliable, supported way to do this. You assign a method reference to an instance of a functional interface, but that instance is cooked up by LambdaMetaFactory
, and there is no way to drill into it to find the method you originally bound to.
Java 中的 Lambda 和方法引用的工作方式与 C# 中的委托截然不同.对于一些有趣的背景,请阅读 invokedynamic
.
Lambdas and method references in Java work quite differently than delegates in C#. For some interesting background, read up on invokedynamic
.
此处的其他答案和评论表明,目前可以通过一些额外的工作来检索绑定方法,但请确保您了解注意事项.
Other answers and comments here show that it may currently be possible to retrieve the bound method with some additional work, but make sure you understand the caveats.
这篇关于如何获取 Java 8 方法引用的 MethodInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!