【问题标题】:Pass reflection method as argument (functional interface)将反射方法作为参数传递(功能接口)
【发布时间】:2020-08-03 17:27:03
【问题描述】:

我有如下功能界面

@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.
}

【问题讨论】:

    标签: java reflection functional-interface


    【解决方案1】:

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

    (假设你正在循环Demo.class.getDeclaredMethods()

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

    method 正好是rockTheWorldTest 时,这或多或少相当于调用doSomething(new Demo()::rockTheWorldTest);,事实上,我认为你必须确保method 的签名“匹配”@987654327 之一@。我会在执行“调用”循环之前过滤testClasMethods,只留下匹配的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2010-10-16
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多