Java反射:根据参数和签名自动调用正确的重载方法

flo*_*w2k 3 java reflection overloading

假设有一个称为重载的方法doTask:

public class Game {
  void doTask(Joker joker);
  void doTask(Batman batman, Robin robin);
}
Run Code Online (Sandbox Code Playgroud)

我想调用正确的方法,给定method("doTask")的名称和一个参数数组,其数量和类型不是先验已知的.

通常,这至少包括三个步骤:
1.找到参数的数量及其类型,并创建一个数组Class[] myTypes.
2.识别正确的重载Method,即Method rightMethod = game.getClass().getMethod("doTask", myTypes);
3.调用方法:rightMethod.invoke(paramArray).

是否存在要求Java反射自动识别要使用的正确重载方法的工具,并使我们不必执行步骤1和步骤2?理想情况下,这就像是:
Library.invoke("doTask", paramArray);

Hol*_*ger 5

有这样的设施java.beans.Statement,resp.Expression如果需要返回值:

Game game = new Game();
Joker joker = new Joker();
Statement st = new Statement(game, "doTask", new Object[]{ joker });
st.execute();
Run Code Online (Sandbox Code Playgroud)

但是,它仅适用于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();
Run Code Online (Sandbox Code Playgroud)