I’m trying to instantiate a class using the Constructor.newInstance() method but am running into trouble properly providing the parameters for the constructor. The problem is, the constructor parameters are made available as a String[] array, the elements of which I have to cast to their corresponding types. This works for objects, but what if some of the parameters are primitive types?
Here’s a simplified example (that seems to work fine until I hit a primitive type):
Class fooClass = Class.forName("Foo");
Constructor[] fooCtrs = fooClass.getConstructors();
Class[] types = fooCtrs[0].getParameterTypes();
Object[] params = new Object[types.length];
for(int i = 0; i < types.length; i++) {
params[i] = types[i].cast(args[i]); // Assume args is of type String[]
}
Once I hit an int or something, I’ll get a ClassCastException.
Am I doing anything wrong? Do I need to manually wrap any primitives I encounter, or is there a built in way of doing that?
Correct, you need to add primitives in a wrapper.
Read about primitives in Constructor.newInstance() docs
Parameters:
initargs – array of objects to be passed as arguments to the constructor call; values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. a float in a Float)