[英]How to create generic methods that take any type parameter?
I have an abstract superservice that should perform some common logic. 我有一个抽象的超级服务,应该执行一些常见的逻辑。 Several services implement this superservice.
几个服务实现了这个超级服务。 I chose the ServiceImpl based on a condition, and want to assign it to the abstract type, for later running the common logic.
我根据条件选择了ServiceImpl,并希望将其分配给抽象类型,以便以后运行通用逻辑。
What is wrong with the following? 以下是什么问题? I'd like to pass into the
process()
method any object that is of / extends BaseResponse
, like FirstResponse
in my example. 我想将
BaseResponse
或扩展BaseResponse
任何对象传递给process()
方法,例如我的示例中的FirstResponse
。
//superservice
abstract class AbstractService<T extends BaseResponse> {
public void process(T t) {
//execute logic that is common to a BaseResponse
}
}
//implementations
class FirstService extends AbstractService<FirstResponse extends BaseResponse> {
}
//usage
AbstractService<? extends BaseResponse> myservice = new FirstService(); //chose by condition
myservice.process(new FirstResponse()); //ERROR
result: 结果:
The method build(capture#2-of ? extends BaseResponse)
in the type AbstractService<capture#2-of ? extends BaseResponse> is not applicable for the arguments (FirstResponse)
//execute logic that is common to a BaseResponse
If that's the case, the flexibility provided by inheritance is enough, you don't really need generics. 如果是这种情况,继承提供的灵活性就足够了,您实际上并不需要泛型。
public void process(BaseResponse t) {
// ...
}
The reason of error is that, the Java compiler only knows myservice
is an AbstractService<? extends BaseResponse>
错误的原因是,Java编译器仅知道
myservice
是AbstractService<? extends BaseResponse>
AbstractService<? extends BaseResponse>
. AbstractService<? extends BaseResponse>
。 It is not wrong to reassign myservice
to a different subclass later: 以后将
myservice
重新分配给另一个子类是没有错的:
AbstractService<? extends BaseResponse> myservice = new FirstService();
myservice = new SecondService(); // <---------- should be ok
myservice.process(new FirstResponse()); // <--- making this bad
would probably be a true error. 可能是一个真正的错误。 If you need to keep the interface of
process(T)
, you have to change the type of myservice
then: 如果需要保留
process(T)
的接口,则必须更改myservice
的类型,然后:
FirstService myservice = new FirstService();
myservice.process(new FirstResponse());
You could do it with generics like this: 您可以使用如下泛型来实现:
abstract class AbstractService<T extends BaseResponse> {
public void process(T t) {
//execute logic that is common to a BaseResponse
}
}
//implementations
class FirstService extends AbstractService<FirstResponse> {
@Override
public void process(FirstResponse firstResponse) {
super.process(firstResponse);
...
}
}
public static void main(String[] args) {
//usage
AbstractService<FirstResponse> myservice = new FirstService();
myservice.process(new FirstResponse());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.