Java:扩展和实现的对象的映射 [英] Java: Map of objects that extend and implement

查看:135
本文介绍了Java:扩展和实现的对象的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个既实现又扩展的对象的映射。他们正在扩展的类(JPanels)我无法控制。然而,我确实可以控制界面。



这就是我所尝试的

 地图< MyEnum,?扩展JPanel& MyInterface的> MYMAP; 

然而,这是编译时错误。



我可以创建一个抽象类,然后让这个子类扩展它,但是这看起来有点沉重(或者是它?)。

对于记录,我正在使用Java 6解决方案


然而,这是一个编译时错误。 / p>

是的。你不能给通配符多个界限。对可以使用通配符的地方以及可以使用类型参数的地方有一些限制。类型参数可以有多个边界,但它们不能有下限。另一方面,通配符可以有下限,但它们没有多个边界。



一种选择是将类型参数声明为类的一部分,并给它多重界限:

  class MyClass< T extends JPanel& MyInterface的> {
地图< MyEnum,T> MYMAP; //现在可以正常工作了

另请参阅:





参考文献:


$ b

I'm trying to make a map of objects that both implement and extend. The class they are extending (JPanels) I have no control over. I do, however, have control over the interface.

This is what I've tried

Map<MyEnum, ? extends JPanel & MyInterface> myMap;

That, however, is a compile time error.

I could make an abstract class and then make the subclasses extend it, but that seems a bit heavy handed (or is it?).

For the record, I'm using Java 6

解决方案

That, however, is a compile time error.

Yes. You can't give multiple bounds to wildcards. There is some restriction on where you can use wildcards, and where you can use type parameters. Type parameters can have multiple bounds, but they can't have lower bounds. Wildcards on the other hand, can have lower bounds, but they don't have multiple bounds.

One option is to have the type parameter declared as a part of your class, and give multiple bounds to it:

class MyClass<T extends JPanel & MyInterface> {
    Map<MyEnum, T> myMap;  // This would work fine now
}

See also:

References:

这篇关于Java:扩展和实现的对象的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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