On Java Generics and subclassing
Due to their implementation by erasure, they face certain limitations.
For example, the following constructor for a class with both compile time and runtime type checking:
class BagOf<T> {
BagOf(Class<T> restrictionClass);
}
is not satisfiable when T is a generic class itself (since there is no
ArraySet<Double>.class
syntax, for example). The best
work-around I know is to drop the T subclassing restriction for
restrictionClass:
class BagOf<T> {
BagOf(Class<?> restrictionClass);
}
The cost is low (obviously no difference at runtime) - you just don’t assert that the developer using your class specifies a restriction class derived from the class T used in the generics. That won’t prevent certain programming errors such as this anymore
BagOf<Integer> bar = BagOf<Integer>(Double.class)
but these shouldn’t be too hard to find/fix anyway.
Before submitting too clever suggestions, please make sure you’ve tested them. For example “if (obj instanceof T)” is not valid java code: since generics are implemented by erasure, T cannot be referenced in runtime statements.
P.S.
It would obviously be nice if the Java syntax would allow
Foo<Bar>.class
(which at runtime would be the same as
Foo.class
, and at complie time would have the result type
Class<Foo<Bar>>
), but currently it does not for all I know.
P.P.S. I’m not looking for “Class<? extends T>”, that is a different situation. The difficult case is when T is a Generic itself, not a subclass.
Update: JM Ibanez pointed me to Neal Gafter’s Super Type Tokens, which apparently are the same as TypeLiteral in Google Guice. Thanks!