Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClass().getMethod("name", unknown)

For a really abstract application I am creating, I need to call methods without knowing their parameter types and only knowing the parameters in a String shape.

Let say I have the method;

getNames(String like, int amount);

and I have a array of strings containing the 2 parameters, so lets say I have;

String[] params = new String[] {"jack", "25"};

Is there any way that I can get and invoke this method using the params array?

like image 569
Thizzer Avatar asked Nov 06 '22 18:11

Thizzer


1 Answers

You could try


String[] params = new String[] {"jack", "25"};
Object[] realParams = new Object[params.length];
Method[] methods = getClass().getMethods();
for (Method method : methods) {
  if (method.getParameterTypes().length == params.length) {
     for (int i = 0; i < method.getParameterTypes().length; i ++) {
        Class<?> paramClass = method.getParameterTypes()[i];
        if (paramClass = String.class) {
           realParams.add(param);
        } else if (paramClass == Integer.class || paramClass == Integer.TYPE) {
           realParams.add(Integer.parseInt(param));
        } else if (other primitive wrappers) {
            ...
        } else {
          realParams.add(null); // can't create a random object based on just string
          // you can have some object factory here, or use ObjectInputStream
        }
     }
     break; // you can continue here if the parameters weren't converted successfully,     
     //to attempt another method with the same arguments count.
  }
}
like image 145
Bozho Avatar answered Nov 12 '22 13:11

Bozho