Java通用符与多个类 [英] Java Generics Wildcarding With Multiple Classes
问题描述
我想有一个Class对象,但我想强制它代表的任何类扩展类A和实现接口B.
我可以做: p>
类< ;?扩展ClassA>
或:
code> Class< ;?扩展InterfaceB>
但我不能这两者。有没有办法做这个?
实际上,你可以如果你想提供多个接口或一个类加接口,你必须有你的通配符看起来像这样:
T延伸ClassA& InterfaceB>
请参阅泛型教程,特别是有界类型参数部分。如果你愿意,你可以列出多个接口,使用& InterfaceName
。
这可以随意复杂。要演示,请参阅 Collections#max
(包含两行)为:
public static< T extends Object&可比较的超级T> T
max(Collection< ;? extends T> coll)
为什么这么复杂?正如Java通用常见问题解答中所述:保留二进制兼容性。 / p>
看起来这不适用于变量声明,但是当在类上放置一个通用边界时,它会工作。因此,要做你想要的,你可能需要跳过几个圈。但你可以做到。你可以这样做,把一个通用的边界放在你的类上,然后:
class classB {}
interface interfaceC {}
public class MyClass< T extends classB& interfaceC> {
Class< T>变量;
}
获取变量
有你想要的限制。有关详情和示例,请查看泛型的第3页在Java 5.0 。注意,在< T extends B& C>
,类名必须先到,接口跟随。当然,你只能列出一个单一的类。
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?
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:
<T extends ClassA & InterfaceB>
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:
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.
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.
这篇关于Java通用符与多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!