【问题标题】:Java interface hierarchy and it's methods with bounded type GenericsJava接口层次结构及其有界类型泛型的方法
【发布时间】:2023-03-09 08:03:01
【问题描述】:

我有一个场景,我发现构建类型层次结构如下:

IComponent(接口)-> AComponent(类)

在这里,我希望 IComponent 包含一个方法 execute(),该方法将由实现此接口的所有类实现。现在,除了组件层次结构之外,我还想要所有组件的请求/响应格式,所以我想到了以下内容:

IComponentRequest -> AComponentRequest

IComponentResponse -> IComponentResponse

现在我想在 IComponent 中声明 execute() 方法,使所有想要实现的类都可以遵循上述请求/响应层次结构的请求和响应类。从代码的角度解释,我目前声明的方法如下:

public interface IComponent<IComponentRequest,IComponentResponse> {

    IComponentResponse execute(IComponentRequest request);
}

我真正想要的是:

<Any type which implements IComponentResponse> execute(<Any type which implements IComponentRequest> request) {
}

我尝试使用以下泛型:

public interface IComponent<REQUEST,RESPONSE> {} 

但在这些情况下,我在调用方法和接收 REQUEST 和 RESPONSE 不是任何特定 java 类型的响应时遇到了实现问题。因此,我再次继续使用正确的接口 IComponentRequest 和 IComponentResponse 但我无法应用有界泛型。

有人可以帮忙解决我在这里缺少什么吗?

【问题讨论】:

  • (1) Java 中不习惯将I 用于接口;我们现在有 IDE。 (2) 注意不要重新发明标准库 API;这看起来像是Function 的克隆。 (至少,extend Function 以便您的自定义实现可以与所有现有基础架构一起使用。)

标签: java generics inheritance interface bounded-types


【解决方案1】:

当您指定通用名称时,您还可以指定类型信息。在这里,您需要 extends 用于每种适当的类型。类似的东西

public interface IComponent<REQUEST extends IComponentRequest,
            RESPONSE extends IComponentResponse> {
    RESPONSE execute(REQUEST request);
}

【讨论】:

  • 我建议使用 &lt;T,R&gt;&lt;I,O&gt; 比 OP 的类型变量更惯用。
  • @Elliot Frisch:这很有帮助。尽管在我的实现类中被覆盖的方法是 public IComponentResponse execute(IComponentRequest request) 我现在使用特定的类型转换来获取请求和响应类型的子类。
  • @chrylis-onstrike- 使用 实际上会生成重写方法:public R execute(T request)。您建议如何在实现接口时声明子类及其方法?我在这里提到了一些例子:public class AComponent&lt;AComponentRequest,AComponentResponse&gt; implements IComponent&lt;T,R&gt;{ 然后调用实现的组件方法的客户端将不得不接收TR 泛型类型。那么在这些情况下我们应该使用显式类型转换吗?
  • @RaviRaiSharma 不要在你的类定义中重新声明新的类型参数。看来您需要复习泛型的基础知识;阅读 the official tutorial 并检查 Collections API 中类的声明(在 java.util 中)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多