aspose file tools
The moose likes Java in General and the fly likes Getting the Class object of a generic type Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Getting the Class object of a generic type" Watch "Getting the Class object of a generic type" New topic
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
    
  14

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
    
    4
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Getting the Class object of a generic type
 
Similar Threads
Generic types on methods and classes
Generics Question.
Help with unchecked call
Why generics work in that strange way?
Transforming a class instance to fit into the generic bracket