我猜你想是這樣:
class MyService implements ContactsService {
@Override
public <T extends Response> T execute(Action<T> action) {
return (T)new GetDetailsResponse();
}
}
這樣做的問題是,我可能有另一個類MyResponse實現響應。然後,我可以打電話:
Action<MyResponse> action = new Action<MyResponse>();
// you can't actually instantiate an interface, just an example
// the action should be some instance of a class implementing Action<MyResponse>
MyReponse r = myService.execute(action);
但execute方法返回GetDetailsResponse的實例,這與MyReponse不兼容。您需要返回類型T,該類型由您傳遞執行的操作給出。
據我可以告訴你不能在執行內部實例化類型T的新變量(不是沒有一些未經檢查的強制轉換)。您可能需要動作類來爲您提供一個可以從execute返回的Response實例。事情是這樣的:
interface Response {
void setWhatever(String value);
}
interface Action<T extends Response> {
T getResponse();
}
class MyAction implements Action<GetDetailsResponse> {
@Override
public GetDetailsResponse getResponse() {
return new GetDetailsResponse();
}
}
class MyService implements ContactsService {
@Override
public <T extends Response> T execute(Action<T> action) {
T response = action.getResponse();
// do something to Response here like
response.setWhatever("some value");
return response;
}
}
接口名稱後缺少''是一個錯字? –
2010-07-14 09:55:06
固定缺失T – Shanta 2010-07-14 09:56:46
'Action'class/interface的簽名是什麼?向我們展示一個編譯器警告的例子。 –
2010-07-14 10:39:28