mercredi 9 août 2017

Java reflection: automatically invoke the right overloaded method based on parameters and signature

Say have an overloaded method called doTask:

public class Game {
  void doTask(Joker joker);
  void doTask(Batman batman, Robin robin);
}

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.

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

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 like:
Library.invoke("doTask", paramArray);





Aucun commentaire:

Enregistrer un commentaire