gpt4 book ai didi

java - 为什么java循环通用规范不允许将 "this"转换为通用实例

转载 作者:行者123 更新时间:2023-12-01 22:33:13 25 4
gpt4 key购买 nike

我可以创建一个循环泛型类依赖项,但不知何故我无法将(没有编译错误)“this”实例转换为泛型引用。据我所知 - 在循环通用场景中创建打破依赖关系的子类是不可能的。

public class P
{
public static abstract class Network<C extends Client<N, C>, N extends Network<C, N>>
{
private C client;

public void addClient(C client)
{
this.client = client;
}
}

public static abstract class Client<N extends Network<C, N>, C extends Client<N, C>>
{
private N network;

public void setNetwork(N network)
{
this.network = network;
}

public void attachOtherClient(C client)
{
network.addClient(client);
}

public void attachSelf()
{
attachOtherClient(this); //does not compile, but it is impossible to create subclasses that breaks this safety (i think)
}
}

public static class TCP extends Network<MK, TCP>
{

}

public static class MK extends Client<TCP, MK>
{
@Override
public void attachSelf()
{
attachOtherClient(this); //compiles without problems
}
}

}

我为我糟糕的英语道歉。

感谢您的帮助。

最佳答案

您应该使用更通用的类:

public static abstract class Network<C extends Client<N, C>, N extends Network<C, N>>
{
private Client<N, C> client; // <== generic type

public void addClient(Client<N, C> client)
{
this.client = client;
}
}

public static abstract class Client<N extends Network<C, N>, C extends Client<N, C>>
{
private Network<C, N> network; // <== generic type

public void setNetwork(N network)
{
this.network = network;
}

public void attachOtherClient(Client<N, C> client)
{
network.addClient(client);
}

public void attachSelf()
{
attachOtherClient(this); // compiles & works: 'this' has type Client<N, C>, not C
}
}

关于java - 为什么java循环通用规范不允许将 "this"转换为通用实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27272857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com