具有类和类的 Java 泛型 一个接口 - 一起
我想要一个 Class 对象,但我想强制它所代表的任何类扩展类 A 并实现接口 B。
我可以:
Class<? extends ClassA>
或者:
Class<? extends InterfaceB>
但我不能两者都做。 有没有办法做到这一点?
I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B.
I can do:
Class<? extends ClassA>
Or:
Class<? extends InterfaceB>
but I can't do both. Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,你可以做你想做的事。 如果您想提供多个接口或一个类加接口,您的通配符必须如下所示:
请参阅 sun.com 上的泛型教程,特别是 有界类型参数 部分,位于这一页。 如果您愿意,您实际上可以使用
& 列出多个接口。 InterfaceName
为您需要的每一个。这可能会变得任意复杂。 要进行演示,请参阅
Collections#max
(包含两行)是:为什么这么复杂? 正如 Java 泛型常见问题解答中所述:为了保持二进制兼容性。
看起来这对于变量声明不起作用,但在类上放置通用边界时确实有效。 因此,要做你想做的事,你可能必须克服一些困难。 但你可以做到。 您可以执行类似的操作,在您的类上放置一个通用边界,然后:
获取具有您想要的限制的变量。 有关更多信息和示例,请查看 Generics in 的第 3 页Java 5.0。 注意,
,类名必须在前,接口在后。 当然,您只能列出一个类。Actually, you can do 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:
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, 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.This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of
Collections#max
, which (wrapped onto two lines) is:why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
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:
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.您不能使用“匿名”类型参数(即使用
?
的通配符)来执行此操作,但可以使用“命名”类型参数来执行此操作。 只需在方法或类级别声明类型参数即可。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.