Double wildcard parameterization (nested wildcard characters) using Java generics

I use a method from a third-party library ( Reflections ), which should find subtypes of this type and looks like

public <T> Set<Class<? extends T>> getSubTypesOf(final Class<T> type) {
...

When the caller code looks like

Class<?> type = ...
Set<Class<?>> subTypes = reflections.getSubTypesOf(type);

I get a compilation error: " cannot convert from Set<Class<? extends capture#19-of ?>> to Set<Class<?>>". The following is the situation:

Class<?> type = ...
Set<?> subTypes = reflections.getSubTypesOf(ht);

therefore, it seems that the only possible remedy for the wrong Set<Class<? extends ?>>will be Set<?>, but not Set<Class<?>>. Why is this so? Thanks for any explanation on this.

+4
source share
4 answers

Use the following instead:

Set<? extends Class<?>> subTypes = reflections.getSubTypesOf(type);

, . a Set<Class<?>> " ", - Set<Class<? extends capture#19-of ?>>, " , - ". " " type T, type (? in Class<?>).

, , " " Number:

Class<Number> type = ...
Set<Class<?>> subTypes = reflections.getSubTypesOf(type);

getSubTypesOf Set<Class<? extends Number>>. Set<Class<?>>, . , Set<? extends Class<?>>. , , null, , .

:

:

+8

? , Class<?>, Set<Class<? extends ?>> ( Java) - (, Class<Number>) Set<Class<? extends Number>>.

+1

: ? extends T ( T) Class (getSubTypesOf ), :

Class<? extends T> type;
Set<Class<? extends T>> subTypesOf = getSubTypesOf(type);

:

Set<Class<?>> subTypes = reflections.getSubTypesOf(type);
+1

"?" "", "".

Set<Class<?>> subTypes = reflections.getSubTypesOf(type);

subTypes - Class 'unknown'. String, Integer, List... .

getSubTypesOf (type) , . "", , . . , , , .

Set<Class> , , .

+1
source

Source: https://habr.com/ru/post/1526947/


All Articles