英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论