Java反射:根据参数和签名自动调用正确的重载方法 [英] Java reflection: automatically invoke the right overloaded method based on parameters and signature
问题描述
假设有一个名为 doTask
的重载方法:
Say have an overloaded method called doTask
:
public class Game {
void doTask(Joker joker);
void doTask(Batman batman, Robin robin);
}
我想调用正确的方法,给出方法的名称 ("doTask"
) 和参数数组,其数量和类型事先未知.
I would like to invoke the right method, given the name of the method ("doTask"
) and an array of parameters whose number and types are not known a priori.
通常,这至少涉及三个步骤:
1. 找出参数的个数和类型,制作一个数组Class[] myTypes
.
2. 识别正确的重载Method
,即Method rightMethod = game.getClass().getMethod("doTask", myTypes);
3.调用方法:rightMethod.invoke(paramArray)
.
Normally, this involves three steps at least:
1. Find the number of the parameters and their types, and make an array Class[] myTypes
.
2. Identify the correct overloaded Method
, i.e. Method rightMethod = game.getClass().getMethod("doTask", myTypes);
3. Invoke the method: rightMethod.invoke(paramArray)
.
是否有一种工具可以让 Java 反射自动识别要使用的正确重载方法,并使我们不必执行步骤 1 和步骤 2?我认为理想情况下,这将是:Library.invoke("doTask", paramArray);
Does there exist a facility to ask Java reflection to automatically identify the right overloaded method to use, and save us from having to do Steps 1 and 2? I'm thinking ideally, this would be like:
Library.invoke("doTask", paramArray);
推荐答案
有这样一个工具,java.beans.Statement
,resp.表达式
如果需要返回值:
There is such a facility, java.beans.Statement
, resp. Expression
if a return value is needed:
Game game = new Game();
Joker joker = new Joker();
Statement st = new Statement(game, "doTask", new Object[]{ joker });
st.execute();
然而,它只适用于 public
方法.
However, it only works for public
methods.
此外,与 java.lang.reflect.Method
不同的是,该工具尚未调整为支持 varargs 参数,因此您必须手动创建参数数组.
Also, unlike java.lang.reflect.Method
, this facility has not been adapted to support varargs parameters, so you have to create a parameter array manually.
可以证明,它可以根据参数类型选择正确的目标方法,这些参数类型不一定与参数类型相同:
It can be demonstrated, that it does the work of selecting the right target method based on the argument types, which are not necessarily identical to the parameter types:
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反射:根据参数和签名自动调用正确的重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!