我有一个接口,其中包含返回或需要实例化类型实例的方法。为此,我创建了形式的类型变量U extends I<U>
以用作返回类型。当然的目的U
是实现类:
interface SelfReferringInterface<U extends SelfReferringInterface<U>> {
}
现在,我有一个实现类,其中包含一个不相关的类型变量:
class RestrictingType<T> implements SelfReferringInterface<RestrictingType<T>> {
}
和一个包装一个实例的类SelfReferringInterface
:
class Wrapper<T extends SelfReferringInterface<T>> {
}
对于Wrapper
采用以下通配符实例的类型,以某种方式我会收到类型推断错误RestrictingType
:
public class Main {
public static void main(String... args) {
// This type checks
SelfReferringInterface<?> test1;
// This too
RestrictingType<?> test2;
// And this
Wrapper<RestrictingType<Object>> test3;
// This fails
Wrapper<RestrictingType<?>> test4;
// Interestingly this does succeed
Wrapper<? extends RestrictingType<?>> test5;
}
}
进行编译会产生以下错误:
Main.java:23: error: type argument RestrictingType<?> is not within bounds of type-variable T
Wrapper<RestrictingType<?>> test4;
^
where T is a type-variable:
T extends SelfReferringInterface<T> declared in class Wrapper
1 error
为什么RestrictingType<?>
不在范围之内T
?为什么功能相似? extends RestrictingType<?>
没有问题?
Wrapper<RestrictingType<T>>
适用于任何给定类型,T
因为我们知道Restricting<T>
实现SelfReferringInterface<RestrictingType<T>>
。但是,Wrapper<RestrictingType<?>>
由于Restricting<? #1>
可能无法实施而无法正常工作SelfReferringInterface<RestrictingType<? #2>>
。通配符?
表示未知类型,在两个地方它们可能是两种不同的未知类型。
这是查看为什么必须这样做的另一种方式:假设您的Wrapper<T>
类可以容纳多个包装类型的项T
。然后,界限<T extends SelfReferringInterface<T>>
意味着应实现任何一项的类型SelfReferringInterface<type of any other item>
,就像如何class SortedList<T extends Comparable<T>>
意味着列表中的任何一项应与列表中的任何其他项具有可比性一样。但是,如果您有一个Wrapper<RestrictingType<?>>
,则可以将RestrictingType<String>
和都添加RestrictingType<Integer>
到其中,因为这两个类型都是的子类型RestrictingType<?>
。但是,RestrictingType<String>
由于没有实施SelfReferringInterface<RestrictingType<Integer>>
,因此合同被打破。
至于为什么Wrapper<? extends RestrictingType<?>>
起作用,我不确定确切如何,但是? extends
通配符意味着您不能在其中添加任何项目,因此您不能使用它来破坏合同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句