Generics are the best we've ever had

November 05, 2007

Several times during the NFJS conference talks, Ted Neward expressed his discontent, bordering on utter disgust, with Java 5 Generics. As he explained it, generics are not a guarantee. Bruce Eckel has given a talk and written a blog entry on the topic, dating back to 2004. If it gives you any indication, the title of Bruce's blog entry is Generics Aren't. What Ted helped to clarify is that by using reflection, it is possible to violate the restrictions that generics are designed to uphold. There isn't much to argue about there. However, I will make the point that while generics aren't, they do provide some intrinsic value. Let's start by defining the problem.

Java 5 Generics works by using "type erasure". This basically means that the information (read effort) that you put into your Java code in the form of angled brackets (no, not XML) is used by the compiler for type-safe checking, then promptly put down the garbage disposal. Thus, at runtime, the type guarantees are absent. It's not all bad though, because there is still a way to get at this information using reflection. But using reflection is a double edge sword since it is also the one responsible for allowing the types to be violated.


Posted at 01:16 AM in Java | Permalink Icon Permalink | Comment Icon Comments (5)