简体   繁体   English

如何使“通用方法声明”接受子类

[英]How to make "generic method declaration" to accept subclasses

I have a interface method:我有一个接口方法:

List<User> getUsers(Query query);

and its implementation:及其实施:

List<User> getUsers(Query query){
..
return users;
}

I can use it without problems:我可以毫无问题地使用它:

Query q = new Query(..);
List<User> users = getUsers(q);

Now I create a subclass of Query:现在我创建一个 Query 的子类:

class UserQuery extens Query{..}

and want to pass an instance of this subclass into getUsers()-method:并希望将此子类的实例传递给 getUsers() 方法:

UserQuery uq = new UserQuery(..);
List<User> users = getUsers(uq); // does not work, as getUsers accepts only "Query"-objects

As defined in the interface, getUsers() only accepts a "Query"-object and not its subclass.正如接口中定义的那样,getUsers() 只接受“查询”对象而不是它的子类。

How can I make the method more generic, so it can accepts Query-Objects but also all its subclasses ?如何使该方法更通用,以便它可以接受 Query-Objects 及其所有子类?

I tried this, but it is not possible in Java:我试过了,但在 Java 中是不可能的:

Interface:界面:

// is not possible in java
List<User> getUsers(<E extends Query> query);

// also not possible in java
List<User> getUsers(Object<? extends MarketdataQuery> query);

Implementation:执行:

// is not possible in java
List<User> getUsers(<E extends Query> query){
..
return users;
}

** **

EDIT:编辑:

** **

It works only when I pass a "Query"-Object:它仅在我传递“查询”对象时才有效:

// This works: 
Query q = new UserQuery(..); 
List<User> users = getUsers(q);


// This does not work:
UserQuery uq = new UserQuery(..);
List<User> users = getUsers(uq);

The get the actual Query-Object, I have to use a cast, so I cannot pass a UserQuery into the method..获取实际的查询对象,我必须使用强制转换,所以我不能将 UserQuery 传递到方法中..

List<User> getUsers(Query query){
    UserQuery uq = (UserQuery) query;
    return users;
}

You can generify method, not only the parameter.您可以泛型方法,而不仅仅是参数。 This will do the work:这将完成以下工作:

<E extends Query> List<User> getUsers(E query);

Now query can be of type Query or any other subclass of it.现在query可以是Query类型或它的任何其他子类。

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

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