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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With