[英]Wildcards to accept any type with interface
我正在嘗試使用泛型來接受任何實現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>
The method makeMove() is undefined for the type Class<capture#7-of ? extends Client>
我究竟做錯了什么?
您正在嘗試調用類java.lang.Class
上的方法,該方法不存在。 你真正需要的是你的類/接口的實現要傳遞給你的方法。
你的connetClient
方法看起來應該是這樣的:
public void connectClient(Client client) {
client.makeMove(); // no more type error
}
當然,如果要在類中保留對此的引用,則必須將Server
類的_client
成員更改為Client
類型。
在這個例子中,我認為你根本不想使用泛型......
試試這個代碼:
public class Server {
private Class<? extends Client> client_;
public void connectClient(Class<? extends Client> client) {
client_ = client;
client.newInstance().makeMove(); // no error here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.