请看下面的代码:
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);
}