如何获取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屋!