简体   繁体   English

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

[英]Wildcards to accept any type with interface

I'm trying to use generics to accept any object that implements the Client interface, but I can't seem to get it right. 我正在尝试使用泛型来接受任何实现Client接口的对象,但我似乎无法做到正确。

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 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> 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. 您正在尝试调用类java.lang.Class上的方法,该方法不存在。 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: 你的connetClient方法看起来应该是这样的:

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 . 当然,如果要在类中保留对此的引用,则必须将Server类的_client成员更改为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 
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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