假设有一个名为 doTask
的重载方法:
public class Game {
void doTask(Joker joker);
void doTask(Batman batman, Robin robin);
}
我想调用正确的方法,给定方法名称 ("doTask"
) 和一组参数,其数量和类型是先验未知的。
通常,这至少涉及三个步骤:
1. 找出参数的个数和类型,组成一个数组Class[] myTypes
。
2. 确定正确的重载Method
,即Method rightMethod = game.getClass().getMethod("doTask", myTypes);
3. 调用方法:rightMethod.invoke(paramArray)
。
是否有一种工具可以要求 Java 反射自动识别要使用的正确重载方法,从而使我们不必执行步骤 1 和 2?我在想理想情况下,这应该是这样的:
Library.invoke("doTask", paramArray);
最佳答案
有这样的设施,java.beans.Statement
,分别Expression
如果需要返回值:
Game game = new Game();
Joker joker = new Joker();
Statement st = new Statement(game, "doTask", new Object[]{ joker });
st.execute();
但是,它只适用于public
方法。
此外,与 java.lang.reflect.Method
不同,此工具还未调整以支持 varargs 参数,因此您必须手动创建参数数组。
可以证明,它根据参数类型选择正确的目标方法,参数类型不一定与参数类型相同:
ExecutorService es = Executors.newSingleThreadExecutor();
class Foo implements Callable<String> {
public String call() throws Exception {
return "success";
}
}
// has to choose between submit(Callable) and submit(Runnable)
// given a Foo instance
Expression ex = new Expression(es, "submit", new Object[]{ new Foo() });
Future<?> f = (Future<?>)ex.getValue();
System.out.println(f.get());
es.shutdown();
关于Java 反射 : automatically invoke the right overloaded method based on parameters and signature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45584386/