Java泛型:有界类型参数中的多重继承
我即将创建一个创建一个类型为T的对象的工厂,它扩展了一个类A和另一个接口I.然而,T不能被知道.以下是最低声明:
public class A { } public interface I { } 这是工厂方法: public class F { public static <T extends A & I> T newThing() { /*...*/ } } 这汇编了一切罚款. 当我尝试使用该方法时,以下工作正常: A $a = F.newThing(); …虽然没有: I $i = F.newThing(); 编译器抱怨:
我不明白为什么清楚地表示“newThing返回某种类型的T,它扩展了类A并实现了接口I”.当分配给A时,所有的工作(因为T扩展了A),但是分配给我不(因为什么?显然返回的东西都是A和I) 另外:当返回一个对象时,说B类的类B扩展A实现我,我需要将其转换为返回类型T,尽管B匹配边界: <T extends A & I> T newThing() { return (T) new B(); } 但是,编译器不会抛出任何警告,如UncheckedCast等. 所以我的问题: >这里出了什么问题? – 编辑:这里完整的代码片段完全使用Eclipse 3.7,为JDK 6设计的项目: public class F { public static class A { } public static interface I { } private static class B extends A implements I { } public static <T extends A & I> T newThing() { return (T) new B(); } public static void main(String... _) { A $a = F.newThing(); // I $i = F.newThing(); } } 编辑:这是一个完整的示例,方法和调用在运行时工作: public class F { public static class A { int methodA() { return 7; } } public static interface I { int methodI(); } private static class B extends A implements I { public int methodI() { return 12; } } public static <T extends A & I> T newThing() { return (T) new B(); } public static void main(String... _) { A $a = F.newThing(); // I $i = F.newThing(); System.out.println($a.methodA()); } } 解决方法
这不会做你期望的. T延伸A&我指出调用者可以指定任何扩展A和I的类型,然后你会返回它.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |