Java Generics and erasure

When I initially began reading about and using generics in Java, I heard the term “erasure”, but forgot it almost as soon as I’d read it. This is mostly because it didn’t really seem to affect my usage of generics at the time. Erasure is the process by which the compiler changes your parameterized generic code into plain old Objects. That’s right – generics are little more than syntactic sugar that give you a little added compile-time type checking. But behind the scenes it’s all being undone. So what effect does this have? Well, for one thing reflection will not work. You can’t check the specific type of something if it’s cast back into a non-parameterized type during compilation. So your ArrayList<Integer> will basically become an ArrayList<object>, which means that dynamic runtime checks and downcasts are still necessary. Sun did this mainly for backwards compatibility with previous versions of Java, which is understandable for the time being. Incidentally, version 2.0 of C# introduces generics for the first time and they chose to give them run-time representation from the beginning. Hopefully Sun will follow suit.

Scroll to Top