1

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?

user3663882
  • 6,957
  • 10
  • 51
  • 92

3 Answers3

2

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();
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
1

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.

mh-dev
  • 5,264
  • 4
  • 25
  • 23
  • That library may make accessing generic type information in signature more convenient, but it is only making available information which is in either class signatures or variable declarations. That would not allow the `foo` method to know the type of `MyClass`. – Brett Okken May 02 '15 at 15:38
1

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();
Rafal G.
  • 4,252
  • 1
  • 25
  • 41