简体   繁体   English

使用 Class<!--? extends Collection--> 作为方法签名

[英]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.在方法签名中,我需要一个参数,它是从 Collection(List、Set 等)扩展的任何 class 类型,因此我可以返回其中的任何一个。

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<?我确实在 Stackoverflow 中搜索了已经解决的答案,找到了这篇文章: 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> Class<? extends Collection> is, in fact, correct. Class<? extends Collection>实际上是正确的。 The problem that I had did refer to the return type of the method, not being able to cast Collection<T> to List<T> .我遇到的问题确实是指方法的返回类型,无法将Collection<T>转换为List<T>

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

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