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";
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.(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 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 parameter to ArrayList constructor and how does it work when I write int.class? If Class.forname is not the right way than how can we make an object of a classname taken as input from user.
Aucun commentaire:
Enregistrer un commentaire