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

5.7k Views Asked by At

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?

4

There are 4 best solutions below

2
On BEST ANSWER

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.
  }
}
0
On

Sounds like metaprogramming. You may want to look into Groovy/Scala if you're set on the JVM platform.

0
On

Look into the Java reflection APIs, they should (though I don't remember for sure) be able to give you the information you need to ascertain the different types of parameters. You'd then have to iterate over the list and intelligently cast each one based on what the reflection API has told you about the method.

0
On

For dynamic programming use a dynamic programming language. Java is not well suited for that kind of stuff.

Have a look at the reflection API anyway, but if you plan to do a lot of programming like that for your application consider other alternatives.