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.
Advertisement
Answer
You can use varargs to simplify this.
public static void main(String[] args) throws Exception { Student student = Student.class .getConstructor(Integer.class, String.class, Boolean.class) .newInstance(2452, "sfhfshsf", true); System.out.println(student); }
The problem you were having was that toArray()
only returns an Object[]
not a Class[]
and it cann’t be just cast to one.
What you could have done was.
Class[] classesArray = (Class[]) classes.toArray(new Class[0]);