user3663882
user3663882

Reputation: 7357

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?

Upvotes: 1

Views: 1077

Answers (3)

Raphael Amoedo
Raphael Amoedo

Reputation: 4465

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();

Upvotes: 2

Rafal G.
Rafal G.

Reputation: 4432

No, it is not possible. In order to have access to generic's type information you would have to do:

public class MyIntegerClass extends MyClass<Integer> {
    // class body
}

and then:

public void main(String[] args){
    MyIntegerClass i = new MyIntegerClass();
    foo(i);
}

and finally, inside your 'foo' method:

Type superclassType = object.getClass().getGenericSuperclass();
Type[] typeArgs =  ((ParameterizedType)superclassType).getActualTypeArguments();

Upvotes: 1

mh-dev
mh-dev

Reputation: 5503

Never tested it with a static method. But the following https://github.com/jhalterman/typetools can be used to get the generic type at runtime.

Upvotes: 1

Related Questions