Java generics - get class?

ryyst picture ryyst · Jan 29, 2011 · Viewed 178.2k times · Source

I got a list, programmed like this: public class MyList<T>. Is there any way to use the T variable to get the name of class (so I can, from within MyList, know if T is String, Socket, etc.)?

EDIT: Nevermind, found the answer here.

Answer

duffymo picture duffymo · Jan 29, 2011

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

    public Foo(Class<T> type) { this.type = type; } 
}

Usage example:

Foo<Integer> test = new Foo<Integer>(Integer.class);