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?
newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized. .
newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException . Class. newInstance() requires that the constructor be visible; Constructor.
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.
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)
The args[i]
may not be casted to the desired type.
Like if you have list "foo"
and type[i].cast()
is expecting int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With