mercredi 14 février 2018

How to dynamically instantiate java classes with varying number of arguments in java?

I have a number of classes with constructors of different kind of perameters. I am getting the class I need to use as well as it's constructor from text as such:

"TheClassIWant parameter1 1234 parameter2 5678"

or:

"AnotherClass parameter1 3456"

I break the above string into a string with the class name ("TheClassIWant") and an array of parameters (p[]). Now I get the class using:

Class<?> cl = Class.forName("TheClassIWant")

and the constructor using:

Constructor<?>[] cons = cl.getDeclaredConstructors();

I can see the parameters of the constructor using:

Class<?>[] types  = cons[1].getParameterTypes();

How can I create a newInstance of the class when I have a number of constructor parameters that may vary each time? For example I could do this:

TheClassIWant cl = cons[1].newInstance(p[1],p[2],p[3],p[4]);

but the string "AnotherClass parameter1 3456" would cause an Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch





Aucun commentaire:

Enregistrer un commentaire