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

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

Pass reflection method as argument (functional interface)

问题

我有以下功能接口

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

我有一个方法

  1. doSomething(Processor processor)

我可以这样调用doSomething

  1. public class Demo {
  2. public void rockTheWorldTest(String text) {
  3. // 处理逻辑
  4. }
  5. }

我可以这样调用它

  1. doSomething(new Demo::rockTheWorldTest);

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

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

I have the below functional interface

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

I have a method

  1. doSomething(Processor processor)

I can call doSomething like this

  1. public class Demo {
  2. public void rockTheWorldTest(String text) {
  3. // Processing
  4. }
  5. }

I can call it like below

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

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

答案1

得分: 1

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

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

  1. doSomething((text) -> {
  2. try {
  3. method.invoke(new Demo(), text);
  4. } catch (Exception e) {
  5. e.printStackTrace();
  6. }
  7. });

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())

  1. doSomething((text) -> {
  2. try {
  3. method.invoke(new Demo(), text);
  4. } catch (Exception e) {
  5. e.printStackTrace();
  6. }
  7. });

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:

确定