Reputation: 21
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?
public Object findModel(long id, Class modelClass) {
Object modelObject = null;
javax.jdo.Query query = persistenceManager.newQuery(modelClass);
query.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;
}
public Foo getFoo(long id) {
Foo modelObject = (Foo)this.findModel(id, Foo.class);
return modelObject;
}
public Boo getBoo(long id) {
Boo modelObject = (Boo)this.findModel(id, Boo.class);
return modelObject;
}
Upvotes: 2
Views: 190
Reputation: 115328
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.
Upvotes: 4
Reputation: 1555
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);
Upvotes: 0