is there a way in java to get an instance of something like Class<List<Object>>
?
views:
884answers:
6
A:
List.class
the specific type of generics is "erased" at compile time.
Jason S
2009-07-03 13:15:24
new List<Object>()
Tom Hawtin - tackline
2009-07-03 13:22:52
hmm... I'm new to the site, i did write that, but it seems it was eaten. Is there a guide somewhere on how to escape the and similar?
Alexander Kjäll
2009-07-03 13:29:26
use backticks to escape code
Jason S
2009-07-03 13:31:01
List is an interface
newacct
2009-07-03 19:14:15
+3
A:
Because of type erasure, at the Class level, all List interfaces are the same. They are only different at compile time. So you can have Class<List>
as a type, where List.class
is of that type, but you can't get more specific than that because they aren't seperate classes, just type declarations that are erased by the compiler into explicit casts.
Yishai
2009-07-03 13:17:39
+2
A:
As mentioned in other answers, Class
represents an erased type. To represent something like ArrayList<Object>
, you want a Type
. An easy way of getting that is:
new ArrayList<Object>() {}.getClass().getGenericSuperclass()
The generic type APIs introduced in 1.5 are relatively easy to find your way around.
Tom Hawtin - tackline
2009-07-03 13:28:15
Not only creating a new object, a new class (in this case an anonymous inner class). But that example should be new ArrayList, no? Making an anonymous list would require you to implement all the methods.
Yishai
2009-07-03 13:49:09
Yishai: Erm yes. And it's getGenericSuperclass not getGenericSupertype. And then there's the issue of implementing multiple interfaces.
Tom Hawtin - tackline
2009-07-03 15:10:19
Jason S: One object who cares? There's ways of doing it without the new, but you are using plenty of memory for code.
Tom Hawtin - tackline
2009-07-03 15:11:33