繁体   English   中英

通配符接受任何带接口的类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM