带有类的 Java 泛型 &一个接口 - 在一起 [英] Java Generics With a Class & an Interface - Together

查看:23
本文介绍了带有类的 Java 泛型 &一个接口 - 在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 Class 对象,但我想强制它代表的任何类扩展类 A 并实现接口 B.

我能做到:

Class

或者:

Class

但我不能两者都做.有没有办法做到这一点?

解决方案

实际上,您可以做您想做的事.如果你想提供多个接口或一个类加接口,你必须让你的通配符看起来像这样:

请参阅 泛型教程,特别是 有界类型参数 部分,位于页面底部.如果您愿意,您实际上可以列出多个接口,使用 &InterfaceName 为您需要的每一个.

这可以变得任意复杂.要演示,请参阅 Collections#max,其中(包含在两行中)是:

public static >吨max(Collection coll)

为什么这么复杂?正如 Java 泛型常见问题解答中所述:为了保持二进制兼容性.>

看起来这不适用于变量声明,但在类上放置通用边界时它确实有效.因此,要做您想做的事,您可能需要跳过几个环节.但是你可以做到.你可以做这样的事情,在你的类上放置一个通用边界,然后:

class classB { }接口 interfaceC { }public class MyClass<T extends classB &接口C>{类多变的;}

获得具有您想要的限制的variable.有关更多信息和示例,请查看 泛型的第 3 页Java 5.0.注意,在 ,类名必须在前,接口在后.当然,您只能列出一个类.

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 泛型 &amp;一个接口 - 在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆