• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Reflection question: how to get the Generic type parameterization from a method's return type?  RSS feed

 
Jake Beard
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have several have methods which return a LinkedList<T>, where T is specified in each class. I'm trying to use Java reflection to retrieve the methods from each class, and then find out what T is parametrized to for that class.

So far, I have the following code:



Unfortunately, "type" evaluates to something like "E". I would expect it to evaluate to a some concrete class, as is expressed in the method signature, so for example LinkedList<AServiceNode>.

If anyone has any insight into where I am going wrong, I would greatly appreciate it if you would let me know. Thanks,

Jake
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out what "type erasure" means and you'll know why this data simply is no longer available during runtime, and so also not through reflection.
 
Jake Beard
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh snap, I found the solutions:

http://www.java2s.com/Code/Java/Reflection/getReturnTypeandgetGenericReturnType.htm

I was using getReturnType, as opposed to getGenericReturnType

Jake
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jake Beard wrote:Oh snap, I found the solutions:

http://www.java2s.com/Code/Java/Reflection/getReturnTypeandgetGenericReturnType.htm

I was using getReturnType, as opposed to getGenericReturnType

Jake



I don't think that method does what you think it does.

Henry
 
Adam Michalik
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Check out what "type erasure" means and you'll know why this data simply is no longer available during runtime, and so also not through reflection.

The generic info is not available during runtime on generic objects, but it is available on generic declarations, ie. Field and Method declarations. And the solution you found should work just fine:


Prints:
[class java.lang.String]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!