Reified generics possible in Java?

The generic implementation is problematic: with the erasure of the generic type information, a instance of type ArrayList<String> is equivalent toArrayList<Long>, basically both runtime instances have the type ArrayList. This allows useful constructs like <?>, but the original generic type is lost at runtime. Since Java 5 I’ve found no way to get the type information back, the “erasuring” seems to be final. But today I’ve found a interesting article at Artima.com, which tells otherwise: Java keeps track of the type information in subclasses! It is possible, with a little bit of utility code, to get back generic argument of the parent class. So you can write a abstract factory class, create a subclass and use it to create instances of this type. This is for my part one of the most missed features I’ve in other languages such as C#.
The article also has a second interesting snippet of code, a version of anonymous sub-classing which is at least uncommon (and easy to recognize).
TypeAwareArrayList<String> stringList = new TypeAwareArrayList<String>(){}; actually builds a anonymous class based on the type of the abstract parent class (see more in the article).

We have to wait (hopefully) for Java 7 to get rid of the erasures, but this article shows a practical way for some of the most missed idioms we have lost.

Advertisements

1 comment so far

  1. Franz Wilhelmstötter on

    I’ve looked at the nice feature wish list for Java 7. But I missed one feature more than reified generics. A real step forward to more reliability an code quality would be a language support for DBC. D shows how it could be. Large software projects would also benefit from “superpackage”s. In comparison, reified generics look like syntactical sugar 😉


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: