Search code examples
javagenericsruntimetype-erasure

Is it possible to get type parameters at runtime?


I know that in Java we don't have paramaterized types at run-time, because of the erasure. But is it possible to get those erased parameters at run-time? Let me provide some example:

public class MyClass<T>{ };

public static void foo(MyClass<?> p){
    //do staff
}

public void main(String[] args){
    MyClass<Integer> i = new MyClass<Integer>();
    foo(i);
}

Now, we passed i to foo as an argument. Is it possible to enquire within the foo's body what type parameter i was instantiated with? Maybe some reflection facility keeps that information at runtime?


Solution

  • Another thing that you can do:

    private Class<T> type;
    
    public MyClass(Class<T> type) {
        this.type = type;
    }
    
    public Class<T> getType() {
        return type;
    }
    

    And then you would instantiate like this:

    MyClass<Integer> i = new MyClass<Integer>(Integer.class);
    

    Not the best way, but it solves the problem. You can access the type inside foo:

    p.getType();