Java Generic Class - Determine Type

generics, java

Solution

I've used a similar solution to what he explains here for a few projects and found it pretty useful.

http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/

The jist of it is using the following:

 public Class returnedClass() {
     ParameterizedType parameterizedType = (ParameterizedType)getClass()
                                                 .getGenericSuperclass();
     return (Class) parameterizedType.getActualTypeArguments()[0];
}

Problem

If I am creating a java class to be generic, such as: ``` public class Foo<T> ``` How can one determine internally to that class, what 'T' ended up being? ``` public ???? Bar() { //if its type 1 // do this //if its type 2 // do this //if its type 3 // do this //if its type 4 // do this } ``` I've poked around the Java API and played with the Reflection stuff, instanceof, getClass, .class, etc, but I can't seem to make heads or tails of them. I feel like I'm close and just need to combine a number of calls, but keep coming up short. To be more specific, I am attempting to determine whether the class was instantiated with one of 3 possible types.

Original source

Related problems