我有一个场景,我发现构建类型层次结构如下:
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/