2013-12-19 29 views
0

我有一个抽象的超级服务应该执行一些通用的逻辑。多个服务实现这个超级服务。我根据条件选择了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) 
+0

是否'与FirstService'工作' BaseResponse',或者'BaseResponse'的任何子类,或者一个特定的子类? – Bohemian

+0

我觉得'AbstractService <?超级BaseResponse> myservice = new FirstService()'应该做的伎俩不是这样吗? –

+0

'FirstService'将与'BaseResponse'一起使用; '? super'会调用'myservice.process()',但是我不能再分配'FirstService' ... – membersound

回答

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()); 
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()); 
} 
+0

但是,例如我不能写:'AbstractService myservice = new SecondService() ;'如果class SecondService '。我想根据条件选择服务,然后在任何服务中运行myservice.process。 – membersound

+0

未经检查的转换是一种简单的方法,但我可以想到'AbstractService myservice =(AbstractService)new FirstService();',但不鼓励。 –

相关问题