So I am using JDK 1.5 and I have a few questions. I am converting an ObjectPool class I had written for non-generics compliant code to use Generics. In my ObjectPool class I have several helper inner classes. One of them is a Creator interface whose implementations are supposed to instantiate a new instance of the Object that is being pooled.
In addition to the Creator interface I supply a static DefaultCreator object that uses the Reflection newInstance() method in order to create a new object. I am having particular trouble figuring out how to do this with Generics.
It seems that I should do something like:
/**
* Defines the method used to instantiate an instance of a pool object. The
* method used, calls newInstance() on the ObjectPools assigned Class type.
*
* @param pool Description of the Parameter
* @return a valid instance of the object type defined in the pool.
*/
public <C> C create(ObjectPool<C> pool) {
C newObject = null;
try {
newObject = Class<C>.newInstance(); // doesn't work
newObject = new C(); // dosen't work
}
catch (Exception e) {
e.printStackTrace();
}
return newObject;
}
The interface defines that ObjectPool<C> is supplied which is why it isn't used in the method. In the original non-generics version of the class the ObjectPool took a Class object to define which types of objects could be pooled. In this method I would call pool.getObjectType().newInstance() in order to instantiate the new class.