Imagine this class:
public class ObjectCreator<T> {
private Class<T> persistentClass;
public ObjectCreator(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
public T create() {
T instance = null;
try {
instance = persistentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return instance;
}
}
Now I sublclass it with a domain object:
public class PersonCreator extends ObjectCreator<Person>{
/**
* @param persistentClass
*/
public PersonCreator() {
super(Person.class);
}
}
All works great…
But if I try to subclass it with a another generic domain object the compiler complains:
public class MessageCreator extends ObjectCreator<Message<String>>{
/**
* @param persistentClass
*/
public MessageCreator() {
super(Message.class);
}
}
The constructor
ObjectCreator<Message<String>>(Class<Message>)is undefined MessageCreator.java
I think that this is a big limit: why is this forbidden?
Any idea how to work around?
Massimo
Try this:
It will be even better if you’ll change constructor of base class to
and then use this in derrived classes:
It will compile without warnings
EDIT
According to definition of
getClass()http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()Returns
Class<? extends X>, where X is the erasure of the static type of the expression on which getClass is called. Which meansgetClass()will returnClass<? extends Message>fornew Message<String>()andClass<? extends Message<String>>for anonymous classnew Message<String>(){}