Java Generic Class - Determine Type

JavaGenerics

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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];
}

Solution 2 - Java

In contrast to .NET Java generics are implemented by a technique called "type erasure".

What this means is that the compiler will use the type information when generating the class files, but not transfer this information to the byte code. If you look at the compiled classes with javap or similar tools, you will find that a List<String> is a simple List (of Object) in the class file, just as it was in pre-Java-5 code.

Code accessing the generic List will be "rewritten" by the compiler to include the casts you would have to write yourself in earlier versions. In effect the following two code fragments are identical from a byte code perspective once the compiler is done with them:

Java 5:

List<String> stringList = new ArrayList<String>();
stringList.add("Hello World");
String hw = stringList.get(0);

Java 1.4 and before:

List stringList = new ArrayList();
stringList.add("Hello World");
String hw = (String)stringList.get(0);

When reading values from a generic class in Java 5 the necessary cast to the declared type parameter is automatically inserted. When inserting, the compiler will check the value you try to put in and abort with an error if it is not a String.

The whole thing was done to keep old libraries and new generified code interoperable without any need to recompile the existing libs. This is a major advantage over the .NET way where generic classes and non-generic ones live side-by-side but cannot be interchanged freely.

Both approaches have their pros and cons, but that's the way it is in Java.

To get back to your original question: You will not be able to get at the type information at runtime, because it simply is not there anymore, once the compiler has done its job. This is surely limiting in some ways and there are some cranky ways around it which are usually based on storing a class-instance somewhere, but this is not a standard feature.

Solution 3 - Java

Because of type erasure, there is no way to do this directly. What you could do, though, is pass a Class<T> into the constructor and hold onto it inside your class. Then you can check it against the three possible Class types that you allow.

However, if there are only three possible types, you might want to consider refactoring into an enum instead.

Solution 4 - Java

The Problem is that most of the Generic stuff will disappear during compilation.

One common solution is to save the type during the creation of the Object.

For a short introduction in the Type Erasure behaviour of java read this page

Solution 5 - Java

If you know a few specific types that are meaningful, you should create subclasses of your generic type with the implementation.

So

public class Foo<T>

public ???? Bar()
{
    //else condition goes here
}

And then

public class DateFoo extends Foo<Date>

public ???? Bar()
{
    //Whatever you would have put in if(T == Date) would go here.
}

Solution 6 - Java

The whole point of a generic class is that you dont need to know the type that is being used....

Solution 7 - Java

It looks like what you want is in fact not a Generic class, but an interface with a number of different implementations. But maybe it would become clearer if you stated your actual, concrete goal.

Solution 8 - Java

I agree with Visage. Generics is for compile-time validation, not runtime dynamic typing. Sounds like what you need is really just the factory pattern. But if your "do this" isn't instantiation, then a simple Enum will probably work just as well. Like what Michael said, if you have a slightly more concrete example, you'll get better answers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondreadwailView Question on Stackoverflow
Solution 1 - Javajnt30View Answer on Stackoverflow
Solution 2 - JavaDaniel SchnellerView Answer on Stackoverflow
Solution 3 - JavaMichael MyersView Answer on Stackoverflow
Solution 4 - JavaJanuszView Answer on Stackoverflow
Solution 5 - JavaRyan ShillingtonView Answer on Stackoverflow
Solution 6 - JavaPaulJWilliamsView Answer on Stackoverflow
Solution 7 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 8 - Javaaberrant80View Answer on Stackoverflow