Java泛型接口实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16568533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java generics interface implementation
提问by Nandan
I have an interface as follows,
我有一个界面如下,
public interface MethodExecutor {
<T> List<T> execute(List<?> facts, Class<T> type) throws Exception;
}
Also, I have a generic implementation like below,
另外,我有一个像下面这样的通用实现,
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;
}
}
Upto this there is no compilation issues,
到目前为止,没有编译问题,
But a specific implementation of this interface fails to compile, The one which shown below.
但是这个接口的一个具体实现编译失败,如下图所示。
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;
}
}
How can I implement this interface for some of the defined objects? Do I need to go for class level generics?
如何为某些已定义的对象实现此接口?我需要去类级别的泛型吗?
回答by Mark Peters
You need to make T
a class type parameter, not a method type parameter. You can't override a generic method with a non-generic method.
您需要创建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
{
//...
}
}
If the element type of facts
should be configurable for a specific implementation, you need to make that a parameter too.
如果facts
应该为特定实现配置元素类型,则您也需要将其设为参数。
public interface MethodExecutor<T, F> {
List<T> execute(List<? extends F> facts, Class<T> type) throws Exception;
}
回答by hoaz
You need to move your generic parameter types from method declaration to interface declaration, so you can parametrize specific implementations:
您需要将泛型参数类型从方法声明移动到接口声明,以便您可以参数化特定的实现:
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 {
...
}
}