Search code examples
javareflectionfunctional-interface

Pass reflection method as argument (functional interface)


I have the below functional interface

@FunctionalInterface
public interface Processor { void handle(String text); }

I have a method

doSomething(Processor processor)

I can call doSomething like this

public class Demo {
    public void rockTheWorldTest(String text) {
    // Processing 
    }
}

I can call it like below

doSomething(new Demo::rockTheWorldTest);

But I wont be able to know the name of the method in a particular class and I want to call this using the reflection from another class

Method[] testClasMethods = DemoAbstractOrchestratorTest.getClass().getDeclaredMethods();
for (Method method : testClasMethods) {
   doSomething(method) // Not able to do this.
}

Solution

  • I don't know the circumstances nor the context that led you to take this approach, but a way of doing it would be:

    (assuming you are looping over Demo.class.getDeclaredMethods())

    doSomething((text) -> {
            try {
                    method.invoke(new Demo(), text);
    
            } catch (Exception e) {
                    e.printStackTrace();
            }
    });
    

    which is equivalent more or less to the call doSomething(new Demo()::rockTheWorldTest); when method is exactly rockTheWorldTest, in fact, I think you have to make sure that method's signature "matches" the one of void handle(String text). I would filter testClasMethods before doing the "invocation" loop leaving just the methods that matches.