problems/limitations of java generics

I love generics. Let me repeat that, I really love generics.

But sometimes they really cause a lot of headaches.

Current trends in libraries is to use annotations, and these annotations are used at runtime to change the classes using javassist or another tool for bytecode manipulation. This is usually based on the principles of aspect oriented programming or inversion of control.

I use two frameworks which work like this very often, EJB3 and tapestry.
In my code I often see a lot of similarities, where class files are the same to a certain extent, and there are only differences in object classes which are used. A wonderful opportunity to split out the shared code and put that in a generic parent class. This class is parameterized using the type for the object classes.

This is a wonderful principle which enhances code reuse, reduces code duplication etc. I normally try to go even one step further and have all the code generated as well (using equanda).

Unfortunately, once this concerns EJB3 or tapestry code, this often fails, and I am still forced to repeat some classes. In java, generics are source-code, compile time information. Though code introspection is one of the powerful features of java, they did not add the ability to have type information of classes which inherit from a generic parent. More specifically say you have the following classes:

public abstract class GenericParent<T extends BaseClass>
    public abstract T getObject();

public class InstantiatedClass 
    extends GenericParent<RealClass>
    pubic RealClass getObject()
        // do whatever needs to be done

On introspecition of “InstantiatedClass” the return type of the “getObject” method will be “BaseClass” and not “RealClass”. I believe this was done to not break backwards compatibility with class files, or with the introspection API. However, this is a serious limitation which hampers the use of generic parent class.
Let’s just hope this will be fixed in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen