1

I have a functional interface and a class using that interface not I would like to have the name of the method of the class and not that of the interface . The code given below :

@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 

    }
}

So the output required should be the method name of the class i.e

myMethod2

provided this method should not execute and nothing should be change

Neeraj
  • 83
  • 2
  • 6

1 Answers1

1

They way the implementation is written, they deliberately don't make this easy to find. This is because they wanted the flexibility to change how it is implemented in the future.

That being said, what you can do is

  • Add an Instrumentation to remember when these lambdas are created and save their bytecode. These lambdas don't have class name, but they do have byte code you can read.
  • You can read the bytecode to see what method they call.

Obviously, this won't work for non trivial lambdas.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    As far as I know, the bytecode of the generated classes was passed to Instrumentation agents in earlier Java 8 implementations only whereas they are now exempted from Instrumentation. But when you are already at Instrumentation agents reading bytecode, you can read the class containing the method reference in the first place, which also contains the information about which method will be invoked. – Holger Mar 07 '19 at 10:40