NoSuchMethodException when parameter of java.lang.Integer is passed in constructor (Reflection)

Viewed 1242

I am trying to declare an ArrayList using Reflection. Below is my code

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException {
    String intClass="java.lang.Integer";   //This string will be replaced by a string taken from user which will be a class name.
    Class classOf=Class.forName("java.util.ArrayList");
    Class[] parameterslist ={Class.forName(intClass)};
    Constructor constructorOfClass=classOf.getConstructor(parameterslist);
}

When I run this code I get

Exception in thread "main" java.lang.NoSuchMethodException: java.util.ArrayList.<init>(java.lang.Integer)

When I modify parameterslist as

Class[] parameterslist={int.class}

it works but I have to take the name of parameter class as input from a user, so I can't directly write int.class.

I have already searched about the difference between Class.forName() and Classname.class but answers like this conclude that they are same. I just want to know why we cannot use Class.forName() object to pass as a parameter to ArrayList constructor and how does it work when I write int.class? If Class.forName() is not the right way then how can we make an object of a classname taken as input from a user?

1 Answers

The ArrayList constructor that you want to use takes as parameter a primitive int and not an Integer class :

public ArrayList(int initialCapacity) 

You provide as argument the Integer class :

String intClass="java.lang.Integer";
...
Class[] parameterslist ={Class.forName(intClass)};

These are not compatible types for reflection usage.

If Class.forname is not the right way than how can we make an object of a classname taken as input from user.

Class.forName() is not the issue here. If you want to create by reflection an object by passing an instance of a specific class as argument of the constructor, the class has to provide a constructor with this type.
For ArrayList, you have only two overloaded constructors with arguments :

public ArrayList(Collection<? extends E> c) 

and

public ArrayList(int initialCapacity) 

So you could retrieve by reflection a constructor with a Collection type or an int type and that's all.

Related