How to get the class of type variable in Java Generics

ZeDonDino picture ZeDonDino · Feb 26, 2013 · Viewed 49.2k times · Source

I've seen similar questions but they didnt help very much.

For instance I've got this Generic Class:

public class ContainerTest<T>
{

    public void doSomething()
    {
        //I want here to determinate the Class of the type argument (In this case String)
    }
}

and Another Class which uses this Container Class

public class TestCase
{

    private ContainerTest<String> containerTest;

    public void someMethod()
    {
        containerTest.doSomething();
    }
}

Is it possible to determinate the Class of the type argument in method doSomething() without having an explicit type variable/field or any constructor in ContainerTest Class?

Update: Changed format of ContainerTest Class

Answer

Didier L picture Didier L · Feb 26, 2013

The only way is to store the class in an instance variable and require it as an argument of the constructor:

public class ContainerTest<T>
{
    private Class<T> tClass;
    public ContainerTest(Class<T> tClass) {
        this.tCLass = tClass;
    }

    public void doSomething()
    {
        //access tClass here
    }
}