简体   繁体   English

如何从适用于多种 Class 类型的方法返回实际类型而不是 Object 类型?

[英]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方法以返回FooBoo类型而不是Object类型

I'd like to be able to just call findModel from FooService or BooService without casting to a Foo or Boo model object.我希望能够从FooServiceBooService调用findModel而无需转换为FooBoo model object。

Is that possible?那可能吗?

SubService:子服务:

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;

}

FooService extends SubService: FooService 扩展子服务:

public Foo getFoo(long id) {

    Foo modelObject = (Foo)this.findModel(id, Foo.class);
    return modelObject;

}

BooService extends SubService: BooService 扩展了 SubService:

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.

相关问题 获取 Class 方法的返回类型与实际返回类型不同 - Return type of get Class method is different from actual returntype 如何从具有泛型返回类型的方法返回实际实例 - How to return an actual instance from a method with a generic return type 从通用模板类型Object调用实际的类方法 - call actual class method from generic template type Object 如何从课程中获取实际的课程类型 <T> 方法参数 - How to get actual class type from Class<T> method argument 具有泛型的类方法返回List <Object> 而不是列表 <PluginSnapshot> 使用原始类型时 - Method of class with generics returns List<Object> rather than List<PluginSnapshot> when using raw type 在实例上调用方法,而不是在不能使用静态类型的类上调用 - Calling the method on an instance rather than the class not working with static type 如何将任何类型的 object 传递给其中包含 Class 类型的方法 - how to pass any type of object into a method that has Class types within it 将多个对象类型传递给具有单个类型的方法 - Pass Multiple object types to method with single type 如何修改此流方法以返回对象而不是列表<Object> ? - How can I amend this streams method to return the Object rather than a List<Object>? java方法返回类型不是实际类型 - java method return type is not actual type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM