Using Reflection: java.reflection.Constructor.newInstance ()

I am trying to create an instance of a class using the Constructor.newInstance () method, but I ran into a problem providing parameters correctly for the constructor. The problem is that the constructor options are made available as an array of String [], the elements of which I must use for their respective types. This works for objects, but what if some of the parameters are primitive types?

Here's a simplified example (which seems to work fine until I find 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[]
}

As soon as I hit the int or something else, I will get a ClassCastException. Am I doing something wrong? Do I need to manually wrap any primitives I come across, or is there a built-in way to do this?

+5
source share
2 answers

That's right, you need to add primitives to the wrapper.

Read about primitives in Constructor.newInstance () docs

Parameters: initargs - an array of objects passed as arguments to the constructor call; primitive type values ​​are wrapped in a wrapper of the corresponding type (for example, float in Float)

+4
source

args[i] cannot be pressed on the desired type.

For example, if you have a list "foo"and are type[i].cast()expectingint

+1
source

All Articles