【随笔·技术】Creating circular generic references

文章取自stackeoverflow上的一个问题的回答,链接在这里


Circular generic references are indeed possible. Java Generics and Collections includes several examples. For your case, such a specimen would look like this:

public interface P2PNetwork,
                            C extends P2PClient> {
  void addClient(C client);
}

public interface P2PClient,
                            C extends P2PClient> {
  void setNetwork(N network);
}

class TorrentNetwork implements P2PNetwork {
  @Override
  public void addClient(TorrentClient client) {
    ...
  }
}

class TorrentClient implements P2PClient {
  @Override
  public void setNetwork(TorrentNetwork network) {
    ...
  }
}

...

TorrentNetwork network = new TorrentNetwork();
TorrentClient client = new TorrentClient();

network.addClient(client);

你可能感兴趣的:(【随笔·技术】Creating circular generic references)