Nick Nick - 7 months ago 10
Java Question

Constructors that use <Class>... with reflection

I am trying to use a constructor for a class with reflection by doing:

<Class>.getConstructor(String.class, Array.newInstance(Car.class).getClass())


when the constructor for the class looks like this:

public <Class>(String var1, Car... var2)


But when the code I try to run that code (and create a new instance of the class) an IllegalArgumentException is thrown.

Answer

Array.newInstance(Car.class).getClass() isn't how you'd get the Class for type Car[]. The correct way to do that would just be

Car[].class

Array.newInstance(Car.class) asks Java for a 0-dimensional array, which is illegal.

Comments