Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics <this??>

Tags:

java

Is there any way you could use a type of the class you're in for a generic argument? for example I have this class 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;
    }

....

}

which is a part of the abstract class NetworkService

public abstract class NetworkService {

    private final Set<ServiceNode<?>> registeredNodes = new HashSet<>();

    public final void register(ServiceNode<?> node) {
        registeredNodes.add(node);
    }

    ...

}

So basically is there anyway to remove the wildcard argument from ServiceNode in the NetworkService class and replace it with whatever type the class is extending NetworkService

like image 362
user1973226 Avatar asked Jan 12 '13 23:01

user1973226


1 Answers

Genericise your base class thus:

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

    private final Set<ServiceNode<T>> registeredNodes;

    ...
}

and then extend from it thus:

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

Google for curiously recurring generic pattern.

like image 199
Oliver Charlesworth Avatar answered Oct 14 '22 15:10

Oliver Charlesworth