Java泛型接口的实现 [英] Java generics interface implementation

查看:221
本文介绍了Java泛型接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口如下,

  public interface MethodExecutor {
< T>列表与LT; T> execute(List<>事实,Class< T>类型)throws Exception;
}

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

  public class DefaultMetodExecutor实现MethodExecutor {

public< T>列表与LT; T>执行(List<>事实,Class< T>类型)抛出异常
{
List< T> result = null;

//一些执行

返回结果;
}
}

这里没有编译问题,



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

  public class SpecificMetodExecutor实现MethodExecutor {

public< Model1>列表与LT;型号1>执行(List< Model2>事实,Class< Model1>类型)抛出异常
{
List< Model1> result = null;

//特定于Model1和Model2的一些实现

返回结果;


$ / code $ / pre

如何为一些定义实现这个接口对象?我需要使用类级别泛型吗?

解决方案

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

  public interface MethodExecutor< T> {
列表< T> execute(List<>事实,Class< T>类型)throws Exception;
}

public class DefaultMethodExecutor实现MethodExecutor< Model1> {
公共列表< Model1>执行(List<>事实,类< Model1>类型)抛出异常
{
// ...
}
}

如果 facts 的元素类型应该可以针对特定实现进行配置,您需要

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


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?

解决方案

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.

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.

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

这篇关于Java泛型接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆