Object Adapters through Dynamic Proxies

Ok, I freely admit that DPs are one of those things I have never used to the extent that I should. This, however, might leap to the forefront as a good reason to use them, because I use adapters all over the place:

The Object Adapter Design Pattern is often used for modifying an interface into another interface that the client expects. A drawback with this pattern is that you need to implement all the methods of the target interface. In this newsletter, solve the problem with dynamice [sic] proxies

In the latest upgrade of my website (many more to come soon) I have added an RSS feed for The Java(tm) Specialists' Newsletter for those who would prefer receiving the newsletter via RSS rather than as an email. The RSS feed will always only have the most current newsletter on it, but the old issues will, as always, still be available for free on our website.
Object Adapter based on Dynamic Proxy

A few weeks ago, I presented my Design Patterns Course to a wonderfully inspiring audience in Austria. One of the three Doctors of Computer Science in the course, Dr Klaus Wiederaenders suggested an approach to solve a problem that had been bugging me with the Object Adapter Pattern.

There are two different types of Adapter Design Patterns: Object Adapter and Class Adapter. The Object Adapter has the advantage that it can be used to adapt a whole hierarchy of objects, whereas the Class Adapter has the advantage that you do not need to override all the methods.
Application of Object Adapter

Java 5 has a neat little feature, that is not widely known. You can change the return type of overridden methods. For example, clone() now returns the correct type of the object, so you do not need to downcast the result anymore.

One of my annoyances with Java has been that Collection.toArray() returns an Object[] and not the correct type. Say you have a collection containing Strings, then you have to pass a String[] into the toArray() method. This seems clumsy to me. It would have been nice if this had been changed in Java 5. However, generics cannot solve the problem due to erasure. There is no handle to the type of generic, once the code has been compiled. You therefore have to change the construction of the collection object to also have a handle to the class of the generic type.

My first solution was to write a Class Adapter, which extended java.util.ArrayList with my adapter, which I called BetterArrayList. I have put these classes in a package so that we can do static imports later on:

Artima