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

huangapple go评论110阅读模式
英文:

Pass reflection method as argument (functional interface)

问题

我有以下功能接口

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

我有一个方法

doSomething(Processor processor)

我可以这样调用doSomething

public class Demo {
    public void rockTheWorldTest(String text) {
    // 处理逻辑 
    }
}

我可以这样调用它

doSomething(new Demo::rockTheWorldTest);

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

Method[] testClasMethods = DemoAbstractOrchestratorTest.getClass().getDeclaredMethods();
for (Method method : testClasMethods) {
   doSomething(method) // 无法这样做。
}
英文:

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

答案1

得分: 1

我不知道导致你采用这种方式的具体情况和背景,但一种做法可能是:

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

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

method确切地等于rockTheWorldTest时,这几乎等同于调用doSomething(new Demo()::rockTheWorldTest);,实际上,我认为你必须确保method的签名与void handle(String text)的签名“匹配”。在执行“调用”循环之前,我建议在testClasMethods上进行过滤,只留下匹配的方法。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月4日 01:27:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定