0

If I have Class<A> cls, is there any way to transform that into Class<A[]> arrCls?

1
  • 5
    what are you trying to do that leads you to ask this question? To prevent us from playing the XY problem game Commented Aug 13, 2014 at 0:21

2 Answers 2

3

I think that it depends on what you need.

If you simply need the Class object for the array type, then approach should work:

  Class<A> cls = ...;
  Object array = Array.newInstance(cls, 1);
  Class<?> arrCls = array.getClass();

That should work if A is a concrete class or a type parameter.

However, if you need arrCls to be declared with the type Class<A[]> ... then I don't know of a way to do it, without resorting to "unsafe" type casts. The newInstance(...) method returns an Object, so you've erased the generic typing.

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

3 Comments

"Array.newInstance(cls, 1)" or even 0
"(I understand that the root issue is that generic type inference in Java cannot make the connection between <A> and <A[]>.)" That's not it at all. A method can easily return Class<T[]> if it wants to. Array.newInstance() doesn't return Class<T[]> precisely because that is not necessarily true -- if cls was int.class, A would be Integer, but arrCls would be the class of int[], not Integer[].
OK ... so I don't understand that. But Integer.TYPE != Integer.class, even though they have the same type (Class<Integer>). I guess it must be that Class<int> is illegal because type parameters can't be primitive types.
1

If you're trying to instantiate a variable with a type of Class<A[]> from Class<A>, then you could use this method:

public static <T> Class<T[]> classToArrayClass(Class<T> type) {
    return (Class<T[]>) Array.newInstance(type, 0).getClass();
}

For example:

Class<String> cls = String.class;
Class<String[]> clsArray = classToArrayClass(cls);
System.out.println(clsArray.isArray());
System.out.println(clsArray.getComponentType().getName());

/* Output:
true
java.lang.String
*/

1 Comment

You've left of that you are ignoring or suppressing an unsafe typecast warning.

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.