Java reflection getting array class of a given cla

2019-07-01 13:07发布

问题:

This question already has an answer here:

  • How to get the Array Class for a given Class in Java? 3 answers

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.

回答1:

I think you want Array.newInstance(c, 0).getClass().



回答2:

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

  • class of one dimensional array of Strings String[].class would be [Ljava.lang.String;,
  • class of two dimensional array of Strings String[][].class would be [[Ljava.lang.String;.
  • and in your case data.Person[].class would be [Ldata.Person;

This means that all you need to do is

  • add [L and ; if type is not array,
  • add another [ 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()+";")