Possible Duplicate:
Why are not all type information erased in Java at runtime?
Java's generics are implemented via type erasure, so I thought it was no possible to get any information about the parameterized type at runtime. However, I found the following class in the Jackson library.
(I've simplified the class slightly for the sake of this example)
public abstract class TypeReference<T> {
final Type _type;
protected TypeReference() {
Type superClass = getClass().getGenericSuperclass();
_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public Type getType() { return _type; }
}
The class provides access to it's parameterized type as the following test demonstrates:
void testTypeReference() {
// notice that we're instantiating an anonymous subclass of TypeReference
TypeReference<CurrencyDto> tr = new TypeReference<CurrencyDto>() {};
assert tr.getType() == CurrencyDto.class
}
This class illustrates that actual type parameters can be retrieved at runtime (using reflection), how is this consistent with the notion that Java Generics are implemented via type erasure?