Java 接口(interface)层次结构及其具有有界类型泛型的方法

标签 java generics inheritance interface bounded-types

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

IComponent(接口(interface))-> AComponent(类)

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

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 类型的响应时面临实现问题。因此,我再次继续使用正确的接口(interface) IComponentRequest 和 IComponentResponse,但我无法应用有界泛型。

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

最佳答案

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

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

关于Java 接口(interface)层次结构及其具有有界类型泛型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59979922/

相关文章:

c++ - 界面的解决方法

class - Grails 域类可以从不是域类的类继承吗?

java金字塔/三角形使用for循环

java - 使用 Swagger 的 CXF REST API 文档

generics - 如何将泛型指定为 "don' t care”?

c++ - 模板继承 - 分配失败

java - 如何从适配器 kotlin 访问 View 元素?

java - 带有gridfs大小限制异常的Spring多部分文件上传

ios - 为什么协议(protocol)的存在元类型会丢失继承信息?

generics - 使用 Rust 空类型作为通用绑定(bind)