I have a class ExampleProperty
that extends the superclass Property
and in a separate class, GameObject
, I have an ArrayList<Property> properties
as well as the following method where Engine.createEngineObject(new ExampleProperty())
simply adds the new ExampleProperty()
to a List and returns it back, propertyId
is an inherited member of Property
, and where properties
is the list of Property
s:
public ExampleProperty addExampleProperty()
{
ExampleProperty temp = (ExampleProperty)Engine.createEngineObject(new ExampleProperty());
temp.propertyId = properties.size();
return temp;
}
I want to generalize this method so I can pass in a Class<?> propertyClass
and have it return an object the same type as propertyClass
(and also perform the cast on line 3?). I'm afraid I'm not familiar enough with generalization yet so any help is appreciated :)
EDIT: This is the revised code after the answer was posted. I forgot to mention a bit of info but I worked through it so here's what I have. It's probably awful but it's mine, it works, and I'm proud of it:
public <T extends Property> T addProperty(Class<T> propertyClass) throws IllegalAccessException, InstantiationException {
Property property = propertyClass.newInstance();
if(propertyClass.getSuperclass() == Engine.class)
{
Engine temp = Engine.createEngineObject(propertyClass.newInstance());
temp.propertyId = properties.size();
return (T)temp;
}
T temp = propertyClass.newInstance();
temp.propertyId = properties.size();
return (T)temp;
}
This might do the trick:
public <T extends Property> T createEngineObject(Class<T> propertyClass) throws IllegalAccessException, InstantiationException {
Property property = propertyClass.newInstance();
// do something...
return property;
}
Although, passing Property
instance seems like a better idea:
public <T extends Property> T createEngineObject(T property) {
// do something...
return property;
}