views:

199

answers:

4

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?

+1  A: 

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

Visionary Software Solutions
A: 

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.

Tyson
+2  A: 

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.
  }
}
Bozho
How can I cast the strings to the required parameter when knowing the method, can you give an example?
MrThys
With that solution you cannot have two methods with the same number of arguments.It is impossible to do it this way unless you were told either the name of the method to execute or the types of the parameters you want to use.
Iker Jimenez
Check my update
Bozho
A: 

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.

Iker Jimenez