3

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.

0

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

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()+";")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.