这个问题在这里已有答案:
我有一个功能接口和一个使用该接口的类,我不想拥有类的方法的名称,而不是接口的名称。代码如下:
@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
如果不应该执行此方法,则不应更改任何内容
他们编写实现的方式,他们故意不会让这很容易找到。这是因为他们希望能够灵活地改变未来的实施方式。
话虽这么说,你能做的是
Instrumentation
来记住创建这些lambda的时间并保存它们的字节码。这些lambdas没有类名,但它们有可以读取的字节代码。显然,这不适用于非平凡的lambdas。