Tuesday, April 29, 2008

Class and Generics

Well, I was working in a Java library I'm developing and I found a little issue(may be lack of knowledge) using Class and Generics together. I'm not sure if could be a better solution, I hope to find it soon.

As you know, from Java 5 and above, the Class class now has a generic parameter, so now it is Class<T>. I have a method with the following contract:

Before Generics:
public Object getObject(String source);

With Generics:
public T getObject(String source);

Where the basic idea is convert the String into an Object. I don't know which kind of object is until Runtime, so I used to use the following code:

// Getting an instance of the object
Class classDefinition = Class.forName( className );
Object result = classDefinition.newInstance();

But now with generics I would like to use them and change my code to this:

// Getting an instance of the object
Class<T> classDefinition = Class.forName( className );
T result = classDefinition.newInstance();

receiving an error from the compiler, since Class<capture-of ?> is not equals to Class<T>. So the only fast and not fancy solution is cast it (LOL so why generics??).

// Getting an instance of the object
Class<T> classDefinition = (Class<T>) Class.forName( className );
T result = classDefinition.newInstance();

My code works, but I would like to not use the down-casting. I'll be digging about this and update this post as soon I find the solution. Comments about this are welcome.

0 comments: