Carmine Giangregorio
Carmine Giangregorio

Reputation: 973

Java: extend from a generic class with a specified type

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?

Upvotes: 1

Views: 79

Answers (1)

aioobe
aioobe

Reputation: 420951

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

Upvotes: 3

Related Questions