So I'm trying to learn to use Reflection in java(so i think its called), so I did a little project to make an object without the optimal Constructor pattern with the "new" word.
Unfortunately, it shows me an error for the class type array for the constructor. Here is my project:
SomeClass.java:
public class SomeClass {
public static void main(String[] args) {
ArrayList<Class> classes = new ArrayList<>();
classes.add(Integer.class);
classes.add(String.class);
classes.add(Boolean.class);
Class[] classesArray = (Class[]) classes.toArray(); //here is where it showes the error
ArrayList<Object> objects = new ArrayList<>();
objects.add(2452);
objects.add("sfhfshsf");
objects.add(true);
Object[] studentObjects = objects.toArray();
Student student = null;
try {
student = Student.class.getConstructor(classesArray).newInstance(
studentObjects);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e1) {
e1.printStackTrace();
}
System.out.println(student);
}
}
Student.java:
public class Student {
int studendID = 0;
String studentName = "";
boolean isSome1 = false;
public Student() {
}
public Student(int studendID, String studentName, boolean isSome1) {
this.studendID = studendID;
this.studentName = studentName;
this.isSome1 = isSome1;
}
@Override
public String toString() {
return "Student [studendID=" + studendID + ", studentName="
+ studentName + ", isSome1=" + isSome1;
}
}
The error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class;
at SomeClass.SomeClass.main(SomeClass.java:16)
What is the right way to do this? Help please.