请看下面的代码:
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);
}
Java 反射 lambda java-8
汪汪一只猫
相关分类