Get generic type from a run-time type parameter in Java

Viewed 49

I've read a lot of other questions out there, but I cannot find one with similar case as mine. Assume I have the following code:

public class TestClass
{
    public Class clazz;

    public TestClass(Object input)
    {
        this.clazz = ........ ?? // how to get String.class from "input" parameter?
    }

    public static void main(String[] args)
    {
        List<String> all = new ArrayList<>();
        new TestClass(all);
    }
}

The constructor of TestClass has 1 parameter which is an Object type. At runtime, it receives a variable of type List, but the actual instance is an ArrayList. Inside the TestClass constructor, I want to extract the generic type of that ArrayList from input parameter. The expected result should be String.class object, which can be stored in clazz variable.

1 Answers

This is not possible in Java because the generic type is only saved during compile type. You cannot get type runtime as you are expecting. Internally it will create every type as Object only which is base class for all java class. This concept is called as type erasure. You can read about it more here.

One way you can do is something like this. It will work only if List is not empty.

public class TestClass{
    public Class clazz;

    public TestClass(List<String> input) {
        if (input instanceof ArrayList) {
            if(!input.isEmpty()){
                this.clazz = input.get(0).getClass();
                System.out.println(clazz);
            }
        }
    }

    public static void main(String[] args) {
        List<String> all = new ArrayList<>();
        all.add("21");
        new TestClass(all);
    }
}
Related