tags:

views:

884

answers:

6

is there a way in java to get an instance of something like Class<List<Object>> ?

A: 

You can get a class object for the List type using:

Class.forName("java.util.List")

or

List.class

But because java generics are implemented using erasures you cannot get a specialised object for each specific class.

jwoolard
A: 
List.class

the specific type of generics is "erased" at compile time.

Jason S
+1  A: 

Sure, just do: new List<Object>();

Alexander Kjäll
new List<Object>()
Tom Hawtin - tackline
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
use backticks to escape code
Jason S
List is an interface
newacct
+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
+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
bizarre... no way to do this w/o creating an object?
Jason S
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
Yishai: Erm yes. And it's getGenericSuperclass not getGenericSupertype. And then there's the issue of implementing multiple interfaces.
Tom Hawtin - tackline
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
A: 

how about

(Class<List<Object>>)(Class<?>)List.class
newacct