5

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 Answers 4

2

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.
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How can I cast the strings to the required parameter when knowing the method, can you give an example?
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.
1

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

Comments

0

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.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.