【问题标题】:interface for generic method after method implemented方法实现后泛型方法的接口
【发布时间】:2020-05-08 22:58:20
【问题描述】:

我目前的情况是:

  • 我有 2 个 maven 模块
  • 模块 1 通常带有接口
  • 具有实现的模块 2 并具有不同 maven 模块 module3(外部项目模块)的特定依赖项
  • 模块 2 具有模块 1 的依赖项
  • 模块1不允许有模块3的依赖
  • 在模块 2 中,我有一个实现接口的方法,该接口继承自我无法更改的 maven 工件
  • 我需要提供一个带有 module1 中方法签名的接口,我已经在 module2 中实现了该方法的签名,显然要为该特定方法签名提供其他指定实现。

module2 中实现的方法签名如下:

 Class MyClass{
   public <T extends Enum<T> & Interface1> Interface2 myMethod(param1, param2...){.....}
}

Interface1 和 Interface2 是 module3 的一部分(我无法修改且 module1 不能将其作为依赖项)

问题是: 如何在模块 1 中创建一个接口,由 MyClass 表单模块 2 使用所需的方法签名来实现?

类似:

模块1:

interface MyInterface{
 <T extends Enum<T> & -->What I should put here<--- > -->What I should put here<--- myMethod(param1, param2...){.....}
}


 class MyClass implements MyInterface{
   public <T extends Enum<T> & Interface1> Interface2 myMethod(param1, param2...){.....}
}

     class MyClass2 implements MyInterface{
   public <T extends Enum<T> & -->Different interface needed here than Interface1<-- > -->Different interface needed here than Interface2<-- myMethod(param1, param2...){.....}
}

有什么想法吗? 我如何克服从 module3 继承的接口(我无法更改也不能将其作为 module1 中的依赖项,只有在 module2 中我可以将其作为依赖项) 基本上是在module1中提供一个更通用的接口方法签名定义来满足module2中方法的签名?

目前它说:两种方法:接口方法和类实现方法具有相同的擦除,但都不会覆盖另一个。

【问题讨论】:

  • 如果模块 1 不知道 Interface1,为什么模块 1需要T 限制为 Interface1?为什么 &lt;T extends Enum&lt;T&gt;&gt; 对于模块 1 来说不够好?
  • 难道不可以在模块1中定义想要的接口,在模块2中调用你不能修改的方法来实现吗?这是一个中间步骤,但允许您尊重两个接口。
  • @Andreas 不需要限制它只需要提供一个方法签名来满足module2中已经实现的方法的定义和其他可能的实现。这里最大的问题是 module3 中的 Interface1 和 Interface2
  • @CristianRamon-Cortes 来自 module2 的方法我可以修改,但是 1 个实现需要满足 Interface1 和 interface2 限制,而第二个实现不应该与这 2 个接口有任何关系。解决方案应该是拥有一个由 Interface1 和 Interface2 扩展的更通用的接口。实现 1 保持这 2 个接口的限制,第二个实现实现更通用的接口。但我不能修改 module3 来添加这个更通用的接口。

标签: java oop java-8


【解决方案1】:

使用推理:

 <A, B, T extends Enum<T> & A> B myMethod(param1, param2...){.....}

并让呼叫站点弄清楚。


恕我直言,当事情变得如此棘手时,泛型被高估了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多