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 ?>
// 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:
Post a Comment