有什么办法可以将您所用的类的类型用于泛型参数?例如我有这个类ServiceNode
public final class ServiceNode<S extends NetworkService> {
private final S service;
private final Client client;
private Object attachment;
public ServiceNode(S service, Client client) {
this (service, client, null);
}
public ServiceNode(S service, Client client, Object attachment) {
this.service = service;
this.client = client;
this.attachment = attachment;
}
public S service() {
return service;
}
....
}
这是抽象类
NetworkService
的一部分public abstract class NetworkService {
private final Set<ServiceNode<?>> registeredNodes = new HashSet<>();
public final void register(ServiceNode<?> node) {
registeredNodes.add(node);
}
...
}
所以基本上无论如何,都可以从
ServiceNode
类的NetworkService
中删除通配符参数,并用该类扩展NetworkService
的任何类型替换它 最佳答案
从而泛化您的基类:
public abstract class NetworkService<T extends NetworkService<T>> {
private final Set<ServiceNode<T>> registeredNodes;
...
}
然后从中扩展出:
public class MyNetworkService extends NetworkService<MyNetworkService> {
...
}
Google奇怪地重复了通用模式。