Skip to content
Advertisement

Use Class 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.

Advertisement

Answer

The usage of 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>.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement