If I have Class<A> cls, is there any way to transform that into Class<A[]> arrCls?
-
5what are you trying to do that leads you to ask this question? To prevent us from playing the XY problem gameMike 'Pomax' Kamermans– Mike 'Pomax' Kamermans2014-08-13 00:21:09 +00:00Commented Aug 13, 2014 at 0:21
Add a comment
|
2 Answers
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.
3 Comments
newacct
"Array.newInstance(cls, 1)" or even 0
newacct
"(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[].Stephen C
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.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
Stephen C
You've left of that you are ignoring or suppressing an unsafe typecast warning.