5

有什么方法可以将您所在的类的类型用于泛型参数?例如我有这门课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

4

1 回答 1

16

因此泛化您的基类:

public abstract class NetworkService<T extends NetworkService<T>> {

    private final Set<ServiceNode<T>> registeredNodes;

    ...
}

然后从它扩展:

public class MyNetworkService extends NetworkService<MyNetworkService> {
    ...
}

谷歌奇怪地重复出现的通用模式

于 2013-01-12T23:20:26.933 回答