2013-05-15 238 views
3

我有一个界面如下,Java泛型接口实现

public interface MethodExecutor { 
    <T> List<T> execute(List<?> facts, Class<T> type) throws Exception; 
} 

另外,我有一个通用的实现类似下面,

public class DefaultMetodExecutor implements MethodExecutor { 

    public <T> List<T> execute(List<?> facts, Class<T> type) throws Exception 
    { 
    List<T> result = null; 

     //some implementation 

     return result; 
    } 
} 

高达这是没有编制的问题,

但是这个接口的具体实现无法编译,如下所示。

public class SpecificMetodExecutor implements MethodExecutor { 

    public <Model1> List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception 
    { 
    List<Model1> result = null; 

    //some implementation specific to Model1 and Model2 

     return result; 
    } 
} 

如何为一些定义的对象实现此接口?我是否需要去上课级仿制药?

+2

对于长的代码片段,请使用代码按钮或缩进4个空格。刻度标记仅用于文本内的代码。 –

+2

究竟是编译器的错误? –

回答

8

您需要制作T类类型参数,而不是方法类型参数。您不能用非泛型方法覆盖泛型方法。

public interface MethodExecutor<T> { 
    List<T> execute(List<?> facts, Class<T> type) throws Exception; 
} 

public class DefaultMethodExecutor implements MethodExecutor<Model1> { 
    public List<Model1> execute(List<?> facts, Class<Model1> type) throws Exception 
    { 
     //... 
    } 
} 

如果facts元素类型应该是可配置的具体实现,你需要做一个参数了。

public interface MethodExecutor<T, F> { 
    List<T> execute(List<? extends F> facts, Class<T> type) throws Exception; 
} 
4

你需要从方法的声明将您的泛型参数类型接口声明,这样你就可以参数化的具体实现:

public interface MethodExecutor<T> { 
    List<T> execute(List<?> facts, Class<T> type) throws Exception; 
} 

public class SpecificMetodExecutor implements MethodExecutor<Model1> { 
    public List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception { 
     ... 
    } 
}