How to return the actual type rather than an Object type from a method that can work for multiple Class types?
Is there any way to modify the findModel
method in SubService
to return a Foo
or Boo
type rather than an Object
type.
I'd like to be able to just call findModel
from FooService
or BooService
without casting to a Foo
or Boo
model object.
Is that possible?
SubService:
public Object findModel(long id, Class modelClass) {
Object modelObject = null;
javax.jdo.Query query = persistenceManager.newQuery(modelClass);
quer开发者_StackOverflow社区y.setFilter("id == idParam");
query.declareParameters("long idParam");
List<Object> modelObjects = (List<Object>) query.execute(id);
if(modelObjects.isEmpty()){
modelObject = null;
}
else{
modelObject = modelObjects.get(0);
}
return modelObject;
}
FooService extends SubService:
public Foo getFoo(long id) {
Foo modelObject = (Foo)this.findModel(id, Foo.class);
return modelObject;
}
BooService extends SubService:
public Boo getBoo(long id) {
Boo modelObject = (Boo)this.findModel(id, Boo.class);
return modelObject;
}
Redefine method with generics:
public <T> T findModel(long id, Class<T> modelClass)
Now it will return what you need and you do not need casting.
Cast your objects in you findModel to SubService
public SubService findModel(long id, Class modelClass) {
return (SubService) modelObject;
}
Then you can drop the casting in fooService
Foo modelObject = this.findModel(id, Foo.class);
精彩评论