如何从Java 8中的方法参考获取方法名称[重复]

问题描述 投票:0回答:1

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

@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

如果不应该执行此方法,则不应更改任何内容

java method-reference functional-interface
1个回答
1
投票

他们编写实现的方式,他们故意不会让这很容易找到。这是因为他们希望能够灵活地改变未来的实施方式。

话虽这么说,你能做的是

  • 添加一个Instrumentation来记住创建这些lambda的时间并保存它们的字节码。这些lambdas没有类名,但它们有可以读取的字节代码。
  • 您可以读取字节码以查看它们调用的方法。

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

© www.soinside.com 2019 - 2024. All rights reserved.