【问题标题】:Generic Type from Interface with Generic Type in Implementation接口中的泛型类型与实现中的泛型类型
【发布时间】:2017-03-20 11:30:02
【问题描述】:

我有一个非常常见的用例与 JAVA 中的泛型有关,我无法集中精力,这怎么可能。

以下示例表明,无法在接口中创建泛型类型以进一步将其作为泛型类型传递到实现方法中。

interface MyInterface <T, I, O>
{
     public T method(T arg);
}    

abstract class MyAbstractClass <I , O> implements MyInterface<List<?>, I , O>
{
     // This cause a syntax-failure! What is wrong with this? 
     // And how can I manage my Generics like this?
     @override
     public abstract List<O> method(List<I> arg); 
}

class MyImplementation extends MyAbstractClass <String , Integer>
{
     List<String> method(List<Integer> arg)
     {
         // ... implementation
     }
}

【问题讨论】:

  • 首先,您的界面没有使用其他两种类型。其次,您将 List> 传递给 MyInterface 并在我的抽象类中分别在方法中使用 List 和 List ,这是错误的,您应该在任何地方都有相同的类型,无论是 O 还是 I 等。

标签: java generics interface abstract


【解决方案1】:

我不确定这是否真的是您想要做的,但这种方式会起作用:

interface MyInterface <T, I, O>
{
    T method(I arg);
}

abstract class MyAbstractClass <O, I> implements MyInterface<List<O>, List<I> , O>
{
    @Override
    public abstract List<O> method(List<I> arg);
}

class MyImplementation extends MyAbstractClass <String , Integer>
{
    @Override
    public List<String> method(List<Integer> arg) {
        // ... implementation
    }
}

【讨论】:

  • 我意识到编译器对重载参数类型进行了严格的检查,但对返回类型没有进行检查。所以我必须准确定义传递参数的类型。我只是将我的对象更改为您提出的类似模型。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
相关资源
最近更新 更多