Skip to main content

RTTI for generics

No replies
Joined: 2004-02-03

Introspection and runtime type information (RTTI) are some of the strong features of Java, so when converting several libraries to use the new and wonderful generics features, I was quite surprised when discovering that generic types have no RTTI. Consequently, if you need runtime type information along with generics features you end up handling the RTTI yourself.

An example:
class Engine {
V vehicle;
Class compatibleWith;
public Engine(Class compatibleWith) {
this.compatibleWith = compatibleWith;
public Class getCompatibleWith() {return compatibleWith;}

Engine truckEngine = new Engine(Truck.class);

Notice that in order to be able to tell what kind of vehicle the engine is compatible with, we have to store the type information ourselves in a class variable. This means that when instantiating the truck engine we have to pass the truck type *both* as generics information *and* as a class.

I would really like to see Java improved to allow RTTI for generics, so a generic class like Engine could ask itself "what kind of engine am I?" without the need of adding your own class parameters. If this was allowed I could simply instantiate a truck engine like this:

Engine truckEngine = new Engine();

and the truck engine would still know that it was meant to be placed under the hood of a truck.