问题描述
我正在编写一个应用程序来在对等网络中执行一些分布式计算。在定义网络时,我有两类P2PNetwork和P2PClient。我希望它们是通用的,所以定义如下:
I am writing an application to do some distributed calculations in a peer to peer network. In defining the network I have two class the P2PNetwork and P2PClient. I want these to be generic and so have the definitions of:
P2PNetwork<T extends P2PClient<? extends P2PNetwork<T>>>
P2PClient<T extends P2PNetwork<? extends T>>
与P2PClient定义了setNetwork(T网络)的方法。我希望用这段代码来描述的是:
with P2PClient defining a method of setNetwork(T network). What I am hoping to describe with this code is:
- 一个P2P网络由一个特定类型的
客户端组成 - P2PClient可能只属于
网络,其客户端由与此客户端相同类型的
(
循环引用)
这对我来说似乎是正确的,但如果我尝试创建一个非通用版本,比如
This seems correct to me but if I try to create a non-generic version such as
MyP2PClient<MyP2PNetwork<? extends MyP2PClient>> myClient;
和其他变体我从编译器收到许多错误。所以我的问题如下:
and other variants I receive numerous errors from the compiler. So my questions are as follows:
- 是一个通用的循环引用,甚至可以是
(我从来没有见过任何明确禁止它的东西) ? - 上述通用定义是
这种循环
关系的正确定义吗?
- 如果它是有效的,是否是正确的
方式来描述这种关系
(即是否有另一个有效的
定义,这在风格上是
的首选)? - 如何正确定义一个
非客户端的非泛型实例和
服务器,并给出适当的通用
定义?
推荐答案
循环泛型引用确实有可能。 包含几个示例。对于你的情况,这样的标本看起来像这样:
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<N extends P2PNetwork<N, C>,
C extends P2PClient<N, C>> {
void addClient(C client);
}
public interface P2PClient<N extends P2PNetwork<N, C>,
C extends P2PClient<N, C>> {
void setNetwork(N network);
}
class TorrentNetwork implements P2PNetwork<TorrentNetwork, TorrentClient> {
@Override
public void addClient(TorrentClient client) {
...
}
}
class TorrentClient implements P2PClient<TorrentNetwork, TorrentClient> {
@Override
public void setNetwork(TorrentNetwork network) {
...
}
}
...
TorrentNetwork network = new TorrentNetwork();
TorrentClient client = new TorrentClient();
network.addClient(client);
这篇关于创建循环泛型引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!