如何从Java 8中的“方法参考”中获取方法名称

时间:2019-03-07 10:21:26

标签: java method-reference functional-interface

我有一个功能接口和一个使用该接口的类,但我不想拥有该类的方法名而不是该接口的名。下面给出的代码:

@FunctionalInterface 
interface MyInterface{  
    void display();  
}  
public class Example {  
    public static void myMethod(){  
    System.out.println("Instance Method");  
    System.out.println(new Object(){}.getClass().getEnclosingMethod().getName());

    }  

    public static void myMethod1(){  
        System.out.println("Instance Method");  
        System.out.println(new Object(){}.getClass().getEnclosingMethod().getName());

        }  
    public static String myMethod2(){  
        return "exec";
        } 
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException {  
    // Method reference using the object of the class
    MyInterface ref = Example::myMethod2;  
    // Calling the method of functional interface 

    }
}

因此所需的输出应该是类的方法名称,即

myMethod2

提供的此方法不应执行,并且不应更改任何内容

1 个答案:

答案 0 :(得分:1)

他们是通过编写实现的方式来实现的,所以故意使查找起来不容易。 这是因为他们希望将来可以灵活更改实施方式。

话虽如此,你能做的是

  • 添加一个Instrumentation来记住何时创建这些lambda并保存其字节码。这些Lambda没有类名,但是它们确实具有您可以阅读的字节码。
  • 您可以阅读字节码以查看其调用的方法。

显然,这不适用于非平凡的lambda。

相关问题