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

For a truly abstract application that I am creating, I need to call methods without knowing their parameter types and only knowing the parameters in string form.

Say I have a method;

getNames(String like, int amount);

and I have an array of strings containing 2 parameters, so let's say that I have:

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

Is there a way I can get and call this method using an array of params?

+5
source share
4 answers

You may 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.
  }
}
+2
source

Sounds like metaprogramming. You can look in Groovy / Scala if you are configured on the JVM platform.

+1
source

API Java, ( ) , . , , API- .

0

. Java .

API , , .

0

All Articles