mardi 29 mai 2018

Java: Dynamically create object from class name, with arguments

I have a Java class whose name is stored in a database, that I want to load at runtime. I am using reflection to try to do this, but the current code throws an InvocationTargetException:

String classname = "my.test.path.Class";
Class<?> cls = Class.forName(classname);
Constructor<?> cons = cls.getConstructors();
for (Constructor<?> con : cons) {
    System.out.println(con.toString()); // Does find the constructor
}
Constructor<?> constructor = cls.getConstructor(Integer.class, Details.class);
ClassInterface object = (ClassInterface) constructor.newInstance(id, details);





Aucun commentaire:

Enregistrer un commentaire