[英]Java generics, a way to enforce either super or subtype
Assume I have a class and a method such as this:假设我有一个 class 和这样的方法:
class MyClass<T> {
void doStuff(Wrapper<T> wrapper) {
//impl.
}
}
Generic bounds of the parameter "wrapper" can be modified to Wrapper<? extends T>
参数“wrapper”的通用边界可以修改为
Wrapper<? extends T>
Wrapper<? extends T>
to make the method accept subtypes of T, and Wrapper<? super T>
Wrapper<? extends T>
以使该方法接受 T 的子类型,并且Wrapper<? super T>
Wrapper<? super T>
to accept super types. Wrapper<? super T>
接受超类型。 However, is there a way to modify MyClass such that it accepts both sub and super types of T (not any type), and there is only one method name?但是,有没有办法修改 MyClass 使其同时接受 T 的子类型和超类型(不是任何类型),并且只有一个方法名称? (there can be overloads)
(可能有过载)
I could simply go with Wrapper<?>
of course, but "accept anything" is not the same as "accept something that's in the class hierarchy for T".当然,我可以简单地使用带有
Wrapper<?>
的 go,但是“接受任何东西”与“接受 T 的 class 层次结构中的东西”不同。 I could also make 2 separate methods, one with <? super T>
我还可以制作 2 种单独的方法,一种带有
<? super T>
<? super T>
and one with <? extends T>
<? super T>
和一个带有<? extends T>
<? extends T>
, but then these methods would need different names, since the signature is the same after erasure. <? extends T>
,但是这些方法需要不同的名称,因为擦除后签名是相同的。
Note: Please consider this a question out of curiosity.注意:出于好奇,请考虑这是一个问题。
You could try the following你可以试试以下
<S extends T> void doStuff(Wrapper<? super S> wrapper)
but would need to double check this satisfies your requirements.但需要仔细检查这是否满足您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.