Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing type of generic in Java

Tags:

java

generics

I have a generic class, says :

MyClass<T>

Inside a method of this class, I would like to test the type of T, for example :

void MyMethod()
{

    if (T == String)
        ...
    if (T == int)
        ...
}

how can I do that ?

Thanks for your help

like image 709
Tim Avatar asked Nov 28 '22 11:11

Tim


1 Answers

You can't, normally, due to type erasure. See Angelika Langer's Java Generics FAQ for more details.

What you can do is pass a Class<T> into your constructor, and then check that:

public MyClass<T>
{
    private final Class<T> clazz;

    public MyClass(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    public void myMethod()
    {
        if (clazz == String.class)
        {
           ...
        }
    }
}

Note that Java does not allow primitives to be used for type arguments though, so int is out...

like image 121
Jon Skeet Avatar answered Dec 05 '22 09:12

Jon Skeet