如何创建采用任何类型参数的泛型方法?

时间:2013-12-19 12:05:40

标签: java generics design-patterns abstract-class

我有一个抽象的超级服务应该执行一些常见的逻辑。有几个服务实现了这个超级服务。我根据条件选择了ServiceImpl,并希望将其分配给抽象类型,以便以后运行公共逻辑。

以下是什么问题?我想将process()方法的任何对象传递给BaseResponse方法,就像我的例子中的FirstResponse一样。

//superservice
abstract class AbstractService<T extends BaseResponse> {
    public void process(T t) {
        //execute logic that is common to a BaseResponse
    }
}

//implementations
class FirstService extends AbstractService<FirstResponse extends BaseResponse> {
}

//usage
AbstractService<? extends BaseResponse> myservice = new FirstService(); //chose by condition
myservice.process(new FirstResponse()); //ERROR

结果:

    The method build(capture#2-of ? extends BaseResponse) 
in the type AbstractService<capture#2-of ? extends BaseResponse> is not applicable for the arguments (FirstResponse)

2 个答案:

答案 0 :(得分:3)

    //execute logic that is common to a BaseResponse

如果是这种情况,继承提供的灵活性就足够了,你真的不需要泛型。

public void process(BaseResponse t) {
    // ...
}

错误的原因是,Java编译器只知道myserviceAbstractService<? extends BaseResponse>。将myservice重新分配给不同的子类并没有错:

AbstractService<? extends BaseResponse> myservice = new FirstService();
myservice = new SecondService(); // <---------- should be ok
myservice.process(new FirstResponse()); // <--- making this bad

可能是一个真正的错误。如果您需要保留process(T)的界面,则必须更改myservice的类型:

FirstService myservice = new FirstService();
myservice.process(new FirstResponse());

答案 1 :(得分:2)

你可以用这样的泛型来做:

abstract class AbstractService<T extends BaseResponse> {
    public void process(T t) {
        //execute logic that is common to a BaseResponse
    }
}

//implementations
class FirstService extends AbstractService<FirstResponse> {
    @Override
    public void process(FirstResponse firstResponse) {
        super.process(firstResponse);
        ...
    }
}

public static void main(String[] args) {
    //usage
    AbstractService<FirstResponse> myservice = new FirstService(); 
    myservice.process(new FirstResponse()); 
}
相关问题