Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 596
Wilco Avatar asked Jun 10 '11 18:06

Wilco


People also ask

What does class newInstance () do?

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. .

What is newInstance method in Java?

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.

What is difference between new operator & newInstance () method?

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.


2 Answers

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)

like image 174
mrk Avatar answered Sep 29 '22 05:09

mrk


The args[i] may not be casted to the desired type.

Like if you have list "foo" and type[i].cast() is expecting int

like image 26
Talha Ahmed Khan Avatar answered Sep 29 '22 07:09

Talha Ahmed Khan