0

Here is my code.

First, I have two classes:

public abstract class AbstractTypeReference<T> {
    public Type type();
    public AbstractTypeReference() {
        Type superClass = getClass().getGenericSuperclass();
        type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    }
}

public class MyTypeReference<T> extends AbstractTypeReference<T> {
    public MyTypeReference() {
        super();
    }
}

Then, I run following code:

MyTypeReference<String> ref = new MyTypeReference<String>();
System.out.println(ref.type.toString());

I expect to get java.lang.String as output, but get T instead. The code was copied from com.fasterxml.jackson.core.type. But it works well. Could anyone tell me what is wrong? And why?

zchen
  • 109
  • 2
  • 7
  • You'd need to use `AbstractTypeReference ref = new AbstractTypeReference() {};` (or `public class MyTypeReference extends AbstractTypeReference{...`). Otherwise, you lose the type information because of erasure. "The code was copied from " Please show where it was copied from. – Andy Turner May 28 '17 at 14:07
  • @AndyTurner Sorry I lose the class. It's from `com.fasterxml.jackson.core.type.TypeReference`. – zchen May 28 '17 at 14:10

0 Answers0