• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to retrieve type of Generic object?  RSS feed

 
Tom Brodhead
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to retrieve the type of a Generic object. Code like this:



...doesn't work. What is the magic formula for retrieving the type in use for a generic object off of the "this" keyword?

(I'd ideally like to construct a method that returns a string stating the type in use...Integer, float, etc.)

~~Tom
 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getComponentType works only for arrays.

I believe there is no way to get the generic parameter, because of type erasure.
 
Campbell Ritchie
Marshal
Posts: 55781
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote: . . . I believe there is no way to get the generic parameter, because of type erasure.
I think you are correct.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, for compatibility reasons, generics are really only a compile-time check. By run-time, it's as if you didn't use them at all. That works fine most of the time, and it allowed generics to be added to the Java Language Specification without making big changes to the byte code. Sometimes though, it's a really pain in the butt. You could hack together a solution to your problem by storing the class you need as a member field.
 
Tom Brodhead
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I puzzled over this far longer than I should have, but it's not my nature to give up. And I've found a solution. There's one sacrifice: you *must* instantiate your class as an anonymous class; by doing so, type erasure doesn't happen. Then you may add this method to your generic class and you'll have access to the type.

If anyone can see a way to simplify this (especially with regards to getting the actual short name of the type from the longer, complete class name), I'd be very interested:



 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!