gpt4 book ai didi

java - 接受具有接口(interface)的任何类型的通配符

转载 作者:行者123 更新时间:2023-11-29 03:35:53 26 4
gpt4 key购买 nike

我正在尝试使用泛型来接受任何实现 Client 的对象界面,但我似乎做对了。

public interface Client {
public void makeMove();
}

public MyClient implements Client {
public MyClient(Server server) {
server.connectClient(this);
}
}

我在上面得到的错误是:The method connectClient(Class<? extends FanoronaClient>) in the type Server is not applicable for the arguments (GUIClient)

具有泛型的服务器:

public class Server {
private Class<? extends Client> client_;

public void connectClient(Class<? extends Client> client) {
client_ = client;
client_.makeMove(); // type error here
}
}

这里的错误是The method makeMove() is undefined for the type Class<capture#7-of ? extends Client>

我做错了什么?

最佳答案

您正试图在类 java.lang.Class 上调用一个方法,这是不存在的。您真正想要的是要传递给您的方法的类/接口(interface)的实现

您的 connetClient 方法应该看起来像这样:

public void connectClient(Client client) {
client.makeMove(); // no more type error
}

当然,如果你想在你的类中保留对此的引用,你必须将 Server 类的 _client 成员也更改为类型 客户端

我认为您根本不想在此示例中使用泛型...

关于java - 接受具有接口(interface)的任何类型的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592258/

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