2010-07-14 46 views
2

实现接口时,我怎样才能实现ContactService接口没有得到警告有关从编译器选中转换避免编译器警告:有界的返回类型

interface ContactsService 
{ 
    <T extends Response> T execute(Action<T> action); 
} 

interface Action<T extends Response> { } 

interface Response{ } 

class GetDetailsResponse implements Response {} 

如果我回到GetDetailsResponse的实例,然后我得到的警告: 未选中压倒一切的:返回类型选中需要转换

这是在谷歌IO GWT的最佳实践演示的例子。

+0

接口名称后缺少''是一个错字? – 2010-07-14 09:55:06

+0

固定缺失T – Shanta 2010-07-14 09:56:46

+1

'Action 'class/interface的签名是什么?向我们展示一个编译器警告的例子。 – 2010-07-14 10:39:28

回答

2

我猜你想是这样:

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

在提问者缺席的情况下,我不得不对此提出赞同,并认为这是发生了什么事情。总之,你不能有一个通用的返回类型,并且返回非泛型的东西! – 2010-07-14 13:39:28

1

要实现ContactsService,你必须能够处理任何种Response。用户可能会向您传递Action<FooResponse>,并期望返回FooResponse,或者可能会给Action<BarResponse>并希望BarResponse。如果你无法做到这一点,那么你不符合接口要求。

如果接口想要接受只支持一种类型的实现,那么它本身就会在<T extends Response>上生成基因,而不仅仅是它的方法。