I’m sure we all remember my angry post about type erasure?
Well I wanted to know more about how Java implements type erasure, so I found this article:
http://today.java.net/pub/a/today/2003/12/02/explorations.html
It’s old, but it effectively mentions that:
[quote]Every type parameter is mapped to the appropriate bound. By this, I mean: the type parameter is erased and replaced with the strongest type the compiler can reasonably assert. Thus, in the case of , T is mapped to Object. In the case of , T is mapped to Rentable, and so on.
[/quote]
So technically, doesn’t this mean that generics DON’T cast at runtime, but at compile time?
However, here is a contradiction:
[quote]Casts are inserted wherever necessary, to ensure that the code compiles.
[/quote]
So from the examples and the like, I figure that if Java can figure out what the type is, it will cast it at runtime and at runtime it will act as though there are no casts.
The only time when generics will force casts at runtime is if Javac can’t find the type.
So would that mean the best way of implementing generics in your code would be to use interfaces?
Of course this doesn’t change the fact you can’t map primitive types. :-\