I am trying to declare an
ArrayList
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);
}
Exception in thread "main" java.lang.NoSuchMethodException: java.util.ArrayList.<init>(java.lang.Integer)
Class[] parameterslist={int.class}
int.class
Class.forName()
Classname.class
Class.forName()
ArrayList
int.class
Class.forName()
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.