简体   繁体   中英

Use Class<? extends Collection> as a method signature

In the method signature, I need a parameter that is any class type that extends from Collection (List, Set, etc), so I can return any of them.

To try to achieve this I did use the following method:

public Collection<T> method(Class<? extends Collection> collectionType) {
    // Do something...
}

However when I try to use it like:

method(List.class);

The following error arises:

Error: java: incompatible types: java.lang.Class<java.util.List> cannot be converted to java.lang.Class<java.util.Collection>

I did search for an answer already solved in Stackoverflow, finding this post: Java - Class<? extends Collection>

But it does not help me to understand the error. I think I'm not understanding the wildcard (?) usage.

The usage of Class<? extends Collection> Class<? extends Collection> is, in fact, correct. The problem that I had did refer to the return type of the method, not being able to cast Collection<T> to List<T> .

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.

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