vendredi 17 juin 2016

Reflection and ClassLoader in Java

I need add a class in my classpath after compile my program.

Then, I used the ClassLoader with Java Reflection, as the code below:

Class NewUnit;
Constructor constructor;

ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();

// Define a class to be loaded.
String classNameToBeLoaded = "monarchs_project.Axe";

NewUnit = myClassLoader.loadClass(classNameToBeLoaded);

constructor = NewUnit.getConstructor(int.class, int.class, int.class, int.class);

NewUnit newUnit  = (NewUnit) constructor.newInstance(1, 1, 1, 1);

The parameters of the Axe class are int.

But it doesn't work. The method getConstructor() not work. Thanks.





Aucun commentaire:

Enregistrer un commentaire