将反射方法作为参数传递(功能接口)

时间:2020-08-03 17:27:03

标签: java reflection functional-interface java-reflection

我具有以下功能界面

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

我有方法

doSomething(Processor processor)

我可以这样叫doSomething

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

我可以这样称呼

doSomething(new Demo::rockTheWorldTest);

但是我无法知道特定类中方法的名称,我想使用另一个类的反射来调用它

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

1 个答案:

答案 0 :(得分:1)

我不知道导致您采用这种方法的情况或背景,但是一种解决方法是:

(假设您正在遍历Demo.class.getDeclaredMethods()

doSomething((text) -> {
        try {
                method.invoke(new Demo(), text);

        } catch (Exception e) {
                e.printStackTrace();
        }
});

doSomething(new Demo()::rockTheWorldTest);恰好是method的情况下,相当于呼叫rockTheWorldTest,实际上,我认为您必须确保method的签名“匹配” void handle(String text)之一。在执行“调用”循环之前,我将过滤testClasMethods,只留下匹配的方法。