Given a Class<T>
is there any way to get a Class<T[]>
without first creating an array via Array.newInstance
? Even that doesn't really do quite what I want because Array.newInstance
would return something of type Object
, so I'd still be left doing an unchecked cast.
Asked
Active
Viewed 78 times
0

Rob I
- 5,627
- 2
- 21
- 28

user1063042
- 273
- 2
- 11
-
1I am not sure I fully understand the question: you do have an instance of some generic class, the generic specified by `T`. Now you want to get a new instance of the generic class where the generic is specified by `T[]`? Like `List
` becomes `List – Dominik Sandjaja Jan 24 '13 at 16:07`? -
related: http://stackoverflow.com/questions/4901128/obtaining-the-array-class-of-a-component-type?lq=1 – Paul Bellora Jan 24 '13 at 20:08
1 Answers
2
Use Class.forName():
Class<?> arrayofTsClass = Class.forName("[L" + tClass.getName() + ";");

Rob I
- 5,627
- 2
- 21
- 28
-
I guess that works, but I'd still need to do an unsafe cast, because Class.forName returns a Class>. I suppose I should clarify, the whole reason I want to obtain a Class
is to use its cast method, so if I have to do a unsafe cast to get one to begin with, there really isn't much point. – user1063042 Jan 24 '13 at 16:07 -
Ah, I understand a little better now. Could you post some of the code as an example - that would help. For example, I can't imagine why you wouldn't just cast it yourself (that's what those `Class` methods are for, the implementation of casts, etc). – Rob I Jan 24 '13 at 16:10
-
1@user1063042 I don't think you can do this without an *unchecked* cast, which is not necessarily an *unsafe* cast. It's just a compiler warning, because while it may indicate a code problem, it may also be perfectly "safe". – matts Jan 24 '13 at 17:05