2010-05-05 191 views
2

我有接口:Java泛型方法覆蓋

public interface CartService extends RemoteService{ 
    <T extends ActionResponse> T execute(Action<T> action); 
} 

我想重寫 '執行' 方法實現:類型的 的方法執行(GetCart)XX:

public class XX implements CartService { 

    @Override 
    public <GetCartResponse> GetCartResponse execute(GetCart action) { 
    // TODO Auto-generated method stub 
    return null; 
    } 
} 

但是編譯器錯誤必須覆蓋或實施超類型方法

GetCart & GetCartResponse:

public class GetCart implements Action<GetCartResponse>{ 

} 


public class GetCartResponse implements ActionResponse { 
    private final ArrayList<CartItemRow> items; 

    public GetCartResponse(ArrayList<CartItemRow> items) { 
     this.items = items; 
    } 

    public ArrayList<CartItemRow> getItems() { 
     return items; 
    } 

} 

如何覆蓋此方法?

+0

@blackliteon:您是否嘗試過'公共 GetCartResponse執行(GetCart動作)'? – bguiz 2010-05-05 13:21:44

回答

2

的問題是接口VS的erausre應該是什麼樣子你IMPL的定義。在您的例子中,你有:

而是根據接口定義的實現方法應爲:

public GetCartResponse execute(Action<GetCartResponse> action); 

所以我認爲你要麼需要改變你的接口的簽名或添加其他類型的參數如:

public interface CartService extends RemoteService{ 
    <T extends ActionResponse, U extends Action> T execute(U action); 
} 

或可能的東西沿着線:

public interface CartService extends RemoteService{ 
    <T extends ActionItem> ActionResponse<T> execute(Action<T> action); 
} 
+0

你是如何在你的第一個代碼片段中爲文本着色的? – 2010-05-05 14:10:45

+0

這是自動語法突出顯示器自動執行的操作,不知道如何或爲什麼。 – 2010-05-06 11:32:16

0

使用

public <GetCartResponse extends ActionResponse> 
    GetCartResponse execute(GetCart action) { 
    //do stuff 
} 

爲在CartService execute方法簽名,它應該工作。

我曾經測試過follwing編譯;只是爲了方便,用和IntegerActionList代替。

CartService:

public interface CartService { 
    <T extends Integer> T execute(List<T> action); 
} 

XX:

public class XX implements CartService { 
    public <T extends Integer> T execute(List<T> action) { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 
} 
1

您的接口指定實施類必須爲所有T extends ActionResponse定義該方法。要定義他們的具體行動和迴應 - 我認爲你的接口需要

public interface CartService<T extends ActionResponse, A extends Action<T>> 
    extends RemoteService { 
     public T execute(A action) 
    } 

,然後實施將

public class XX implements CartService<GetCartResponse,GetCart> { 
//... 
} 

至於寫的,你可能不需要有明確的參數化Action類型的擴展 - 只要您可以處理由GetCartResponse進行參數化並且不依賴於GetCart操作的詳細信息的任何種類的Action。在這種情況下,你的界面應該是這個樣子:

public interface CartService<T extends ActionResponse> extends RemoteService { 
public T execute(Action<T> action); 
} 

和實施

public class XX implements CartService<GetCartResponse> { 
public GetCartResponse execute(Action<GetCartResponse> action) { 
    //... 
} 
}