Java 通配符,用于接受具有接口的任何类型

Java 通配符,用于接受具有接口的任何类型,java,generics,Java,Generics,我试图使用泛型来接受实现客户机接口的任何对象,但我似乎无法正确使用它 public interface Client { public void makeMove(); } public MyClient implements Client { public MyClient(Server server) { server.connectClient(this); } } 我在上面看到的错误是:方法connectClient(Class您正试图调用该类上不存在的方法。您真

我试图使用泛型来接受实现
客户机
接口的任何对象,但我似乎无法正确使用它

public interface Client {
  public void makeMove();
}

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

我在上面看到的错误是:
方法connectClient(Class您正试图调用该类上不存在的方法。您真正想要的是将类/接口的实现传递给您的方法

您的
connetClient
方法应该如下所示:

public void connectClient(Client client) {
    client.makeMove(); // no more type error
}
当然,如果您想在类中保留对此的引用,则必须将
服务器
类的
客户端
成员也更改为
客户端
类型


我认为在本例中,您根本不想使用泛型…

您试图对不存在的类调用一个方法。您真正想要的是将类/接口的实现传递给您的方法

您的
connetClient
方法应该如下所示:

public void connectClient(Client client) {
    client.makeMove(); // no more type error
}
当然,如果您想在类中保留对此的引用,则必须将
服务器
类的
客户端
成员也更改为
客户端
类型

我认为您根本不想在本例中使用泛型…

请尝试以下代码:

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

      public void connectClient(Class<? extends Client> client) {
        client_ = client;
        client.newInstance().makeMove(); // no error here 
      }
    }
公共类服务器{
私有类请尝试以下代码:

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

      public void connectClient(Class<? extends Client> client) {
        client_ = client;
        client.newInstance().makeMove(); // no error here 
      }
    }
公共类服务器{

私有类为什么MyClient类不从实现接口实现makeMove方法?为什么MyClient类不从实现接口实现makeMove方法?