I'm trying to use generics to accept any object that implements the Client
interface, but I can't seem to get it right.
public interface Client {
public void makeMove();
}
public MyClient implements Client {
public MyClient(Server server) {
server.connectClient(this);
}
}
The error I get above is: The method connectClient(Class<? extends FanoronaClient>) in the type Server is not applicable for the arguments (GUIClient)
The server with generics:
public class Server {
private Class<? extends Client> client_;
public void connectClient(Class<? extends Client> client) {
client_ = client;
client_.makeMove(); // type error here
}
}
And the error here is 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>
What am I doing wrong?
You are trying to call a method on the class java.lang.Class
, which doesn't exist. What you actually want is an implementation of your class/interface to be passed to your method.
Your connetClient
method should look something like this instead:
public void connectClient(Client client) {
client.makeMove(); // no more type error
}
Of course if you want to keep a reference to this in your class, you will have to change the _client
member of your Server
class to also be of type Client
.
I don't think you want to be using generics at all in this example...
Try this code out :
public class Server {
private Class<? extends Client> client_;
public void connectClient(Class<? extends Client> client) {
client_ = client;
client.newInstance().makeMove(); // no error here
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.