[英]How to create generic methods that take any type parameter?
我有一個抽象的超級服務,應該執行一些常見的邏輯。 幾個服務實現了這個超級服務。 我根據條件選擇了ServiceImpl,並希望將其分配給抽象類型,以便以后運行通用邏輯。
以下是什么問題? 我想將BaseResponse
或擴展BaseResponse
任何對象傳遞給process()
方法,例如我的示例中的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)
//execute logic that is common to a BaseResponse
如果是這種情況,繼承提供的靈活性就足夠了,您實際上並不需要泛型。
public void process(BaseResponse t) {
// ...
}
錯誤的原因是,Java編譯器僅知道myservice
是AbstractService<? extends BaseResponse>
AbstractService<? 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());
您可以使用如下泛型來實現:
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.