[英]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 .有没有办法修改
SubService
中的findModel
方法以返回Foo
或Boo
类型而不是Object
类型。
I'd like to be able to just call findModel
from FooService
or BooService
without casting to a Foo
or Boo
model object.我希望能够从
FooService
或BooService
调用findModel
而无需转换为Foo
或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;
}
Redefine method with generics:用 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
将 findModel 中的对象转换为
SubService
public SubService findModel(long id, Class modelClass) {
return (SubService) modelObject;
}
Then you can drop the casting in fooService然后你可以在 fooService 中删除铸件
Foo modelObject = this.findModel(id, Foo.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.