Java泛型的双通配符参数化(嵌套通配符) [英] Double wildcard parameterization (nested wildcards) with Java generics
问题描述
我正在使用第三方库( Reflections )中的一种方法查找给定类型的子类型,看起来像
I am using a method from a third party library (Reflections) which is supposed to find subtypes of the given type and looks like
public <T> Set<Class<? extends T>> getSubTypesOf(final Class<T> type) {
...
当呼叫者代码看起来像
Class<?> type = ...
Set<Class<?>> subTypes = reflections.getSubTypesOf(type);
我收到一个编译错误:"cannot convert from Set<Class<? extends capture#19-of ?>> to Set<Class<?>>
".以下解决了这种情况:
I am getting a compile error: "cannot convert from Set<Class<? extends capture#19-of ?>> to Set<Class<?>>
". The following fixes the situation:
Class<?> type = ...
Set<?> subTypes = reflections.getSubTypesOf(ht);
,因此看来对于Set<Class<? extends ?>>
错误的唯一可能的补救方法是Set<?>
,而不是Set<Class<?>>
.为什么会这样呢?
感谢您对此的任何解释.
so it looks like the only possible remedy for incorrect Set<Class<? extends ?>>
would be Set<?>
but not Set<Class<?>>
. Why is it so?
Thanks for any explanation on this.
推荐答案
请改用以下内容:
Set<? extends Class<?>> subTypes = reflections.getSubTypesOf(type);
The problem is that nested wildcards don't perform type capture. Declaring a Set<Class<?>>
means "a set of classes of any type", while what's being returned is a Set<Class<? extends capture#19-of ?>>
, which means "a set of classes of any type extending from some specific unknown type". In this case, that "specific unknown type" is derived from the type argument to T
, which is inferred from type
to be an unbounded wildcard capture (the ?
in Class<?>
).
例如,假设特定的未知类型"为Number
:
For example, pretend that "specific unknown type" is Number
:
Class<Number> type = ...
Set<Class<?>> subTypes = reflections.getSubTypesOf(type);
此处,getSubTypesOf
返回Set<Class<? extends Number>>
.该类型不能分配给Set<Class<?>>
,因为
Here, getSubTypesOf
returns a Set<Class<? extends Number>>
. That type is not assignable to Set<Class<?>>
because generic types aren't covariant. But, wildcard capture helps us express covariance, allowing types like Set<? extends Class<?>>
. The caveat is that we can't add anything but null
to such a set, since we don't know its specific type.
相关帖子:
- Java Generic List<List<? extends Number>>
- Multiple wildcards on a generic methods makes Java compiler (and me!) very confused
- What is PECS (Producer Extends Consumer Super)?
类似的帖子:
- Java: Wildcard Types Mismatch Results in Compilation Error
- Issue with declaration of Map<String,Class<? extends Serializable>>
- Bounded-wildcard related compiler error
这篇关于Java泛型的双通配符参数化(嵌套通配符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!