user3294746
user3294746

Reputation: 21

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.

Upvotes: 0

Views: 2189

Answers (1)

Adam
Adam

Reputation: 416

int.class is not a valid class. You need to use the Type static variables in the wrapper classes in order to get a class object for a primitive type. Your getConstructor call you should look like the following.

constructor = NewUnit.getConstructor(java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Integer.TYPE);

Upvotes: 1

Related Questions