| Author |
Getting the Class object of a generic type
|
Hopea Tassu
Greenhorn
Joined: Sep 23, 2009
Posts: 6
|
|
Is it possible to get and store the type of a generic variable somehow like you can use the class literal String.class?
If the method is called as <String>, the variable c should contain String.class.
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56549
|
|
|
It is not possible.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
And the reason is type erasure. Look it up.
Unfortunately, var.getClass() won't help you either, and the following example shows why:
Because of polymorphism and interfaces, you can never say that calling getClass() on a reference with type X will return Class<X>.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
|
|
Welcome to JavaRanch
To elaborate on what Bear has told you: Java does generics by type erasure, so the actual type parameter <String> vanishes entirely at runtime. You can identify the type of one of the elements of a Collection, but that is not necessarily the same as the type of the actual type parameter.
Simpler tutorial here.
|
 |
 |
|
|
subject: Getting the Class object of a generic type
|
|
|