tags:

views:

247

answers:

1

I statically recompiled a Java lib which used generics a lot, like Collection<?>, but the emitted .NET dll only uses Collection, not with type parameters. How come?

+4  A: 

Java generics are dealt by the Java compiler and are converted to non-generic version at compile time. This is different from .NET where the CLR has first class support for type parameters. At the bytecode level, ArrayList<T> will just be a simple ArrayList.

To quote Java docs:

Generics are implemented by the Java compiler as a front-end conversion called erasure, which is the process of translating or rewriting code that uses generics into non-generic code (that is, maps the new syntax to the current JVM specification). In other words, this conversion erases all generic type information; all information between angle brackets is erased. For example, LinkedList<Integer> will become LinkedList. Uses of other type variables are replaced by the upper bound of the type variable (for example, Object), and when the resulting code is not type correct, a cast to the appropriate type is inserted.

Mehrdad Afshari
I dislike Java generics for this reason. Generics should have been a major feature, but instead it wasn't much more than syntactic sugar for avoiding casting `object`s to a specific type. Sugar is wonderful, but it could have been so much more. Mumble types and so do actually add value though, so it's not all bad.
Joren
@Joren, you're being unnecessarily harsh on generics. While type erasure is certainly dissappointing, generics are certainly a clear step up over having to cast from Object as we are now able to have all the compile-time guarantees of the Java type system with our genericized classes.
Falaina