So i'm trying to learn to use the Reflaction subject in java(so i think its called), so i did a little project to try and see how to make an object without the optimal Constructor pattern with the "new" word.
unfortunately, it shows me an error about the making the class types array for the contructor. 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)
if i'm doing it wrong, so what is the right way? help please.