2

Given a Class<?> that describes class A, is it somehow possible to get the Class<?> that matches the class A[]?

Class<?> clazz = A.class;
Class<?> arrayclazz = clazz.toArray(); // ??

assert arrayclazz.equals(A[].class);

2 Answers 2

5

java.lang.reflect.Array.newInstance(clazz, 0).getClass()

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

5 Comments

Thats a neat trick. But is there anyway to save the new instance?
@Idan K You could hack the strings, but the overhead of creating a zero-length array is tiny. Probably less than that of creating intermediate Strings and StringBuilders and then parsing that and looking up the classes. Of course, best would be to avoid reflection and indeed reference arrays altogether.
@Tom: that makes sense. I'm just a little surprised there isn't anything in Java to do this directly without resorting to these kind of tricks.
@Idan K It's not like such a thing should get used much!
@Tim: agreed. The only reason I had to resort to this trickery is because of this ideone.com/OChQB The first call to getGenericReturnType returned int[] but the second returned GenericArrayType and I was only able to get the component from it, i.e. int.
-1

use A[].class. I hope this help.

1 Comment

A was used as an example. I actually just have a Class<?> in hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.