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?