1

I'm trying to extend a generic class, like:

public class GenericClass<T> implements GenericClassInterface<T>
{
     public T myMethod(String typeID) {
        T test = _get_test_value_; // here I use jackson to retrieve T de-serialized from JSON
        return T;
     }
}

Then I extend that class:

public class SpecificClass extends GenericClass<CustomType> implements SpecificClassInterface
{
     public CustomType getIstance(String typeID) {
          return super.myMethod(typeID);
     }
}

The code compiles correctly, but when I debug I find out that type T, when myMethod is called from SpecificClass, is Object, and not CustomType, even if I specified CustomType when I extended GenericClass in SpecificClass.

How come? Is this a limitation of generics in Java?

SubOptimal
  • 20,523
  • 3
  • 44
  • 57
Carmine Giangregorio
  • 833
  • 2
  • 13
  • 32

1 Answers1

2

The type parameter T is not available in runtime (during debugging). This is indeed a limitation of generics in Java and referred to as type erasure. (All type parameters are transformed to Object as you have observed.)

See for instance

Community
  • 1
  • 1
aioobe
  • 383,660
  • 99
  • 774
  • 796
  • Then what is the reason to have extended the GenericClass passing a type to T, as in "extends GenericClass"? It's totally useless? And, if so, how can I implement/simulate a real generic in Java? – Carmine Giangregorio Mar 05 '15 at 10:29
  • The T is around just for type checking purposes. I'm not sure why you say it's useless. A common trick is to pass the Class-object to the constructor. See for instance the constructor of [`EnumMap`](http://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html#EnumMap%28java.lang.Class%29). – aioobe Mar 05 '15 at 14:25
  • @CarmineGiangregorio, did you understand my answer? Or do you want me to elaborate on something? – aioobe Mar 09 '15 at 07:40