多个类的 Java 泛型通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/745756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Generics Wildcarding With Multiple Classes
提问by Alex Beardsley
I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B.
我想要一个 Class 对象,但我想强制它代表的任何类扩展类 A 并实现接口 B。
I can do:
我可以:
Class<? extends ClassA>
Or:
或者:
Class<? extends InterfaceB>
but I can't do both. Is there a way to do this?
但我不能两者兼得。有没有办法做到这一点?
采纳答案by Eddie
Actually, you cando what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
其实,你可以为所欲为。如果你想提供多个接口或一个类加接口,你必须让你的通配符看起来像这样:
<T extends ClassA & InterfaceB>
See the Generics Tutorialat sun.com, specifically the Bounded Type Parameterssection, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
请参阅sun.com 上的泛型教程,特别是页面底部的有界类型参数部分。如果您愿意,您实际上可以列出多个接口,& InterfaceName
为您需要的每个接口使用。
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
这可以变得任意复杂。为了演示,请参阅 的 JavaDoc 声明Collections#max
,其中(包含在两行中)是:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
为什么这么复杂?正如 Java 泛型常见问题解答中所说:为了保持二进制兼容性。
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
看起来这不适用于变量声明,但在类上放置通用边界时确实有效。因此,要做您想做的事,您可能需要跳过几个环节。但是你可以做到。你可以做这样的事情,在你的类上放置一个通用边界,然后:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
得到variable
你想要的限制。有关更多信息和示例,请查看Java 5.0 中的泛型的第 3 页。注意,在 中<T extends B & C>
,类名必须在前,接口在后。当然,您只能列出一个类。
回答by user2861738
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
您不能使用“匿名”类型参数(即使用 的通配符?
)来执行此操作,但可以使用“命名”类型参数来执行此操作。只需在方法或类级别声明类型参数。
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}