So I have this Class c, and I want to get the Class object that represents an array of the type c represents. Is it possible? I can't find any way...
Clarifying: somewhere else I have:
Class<?> c = Class.forName("data.Person");
OK, so I have this class c now. And I want to have the Class that represents the array of persons. The same as if I did:
Class<?> cs = data.Person[].class;
But I want to do it with reflection. I know nothing about the original class, but the reference c to it.
I think you want Array.newInstance(c, 0).getClass().
To create Class instance of some array type you can also use Class.forName(). You just need to surround base type with [L and ; (numbers of [ is number of dimensions), so
String[].class would be [Ljava.lang.String;, String[][].class would be [[Ljava.lang.String;. [Ldata.Person;This means that all you need to do is
[L and ; if type is not array, [ at start if type is already array.So for dynamic c you can use something like
Class.forName(c.isArray()?"["+c.getName():"[L"+c.getName()+";")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With