我即将创建一个创建一个类型为T的对象的工厂,它扩展了一个类A和另一个接口I.然而,T不能被知道.以下是最低声明:
public class A { }
public interface I { }
这是工厂方法:
public class F {
public static T newThing() { /*...*/ }
}
这汇编了一切罚款.
当我尝试使用该方法时,以下工作正常:
A $a = F.newThing();
…虽然没有:
I $i = F.newThing();
编译器抱怨:
Bound mismatch: The generic method newThing() of type F is not applicable for the arguments (). The inferred type I&A is not a valid substitute for the bounded parameter
我不明白为什么清楚地表示“newThing返回某种类型的T,它扩展了类A并实现了接口I”.当分配给A时,所有的工作(因为T扩展了A),但是分配给我不(因为什么?显然返回的东西都是A和I)
另外:当返回一个对象时,说B类的类B扩展A实现我,我需要将其转换为返回类型T,尽管B匹配边界:
T newThing() {
return (T) new B();
}
但是,编译器不会抛出任何警告,如UncheckedCast等.
所以我的问题:
>这里出了什么问题?
>在工厂方法中,是否有一个容易实现所需行为(即分配给静态A或I类变量)的方法,就像通过转换来解决返回类型问题一样?
>为什么A的作业工作,而我没有?
–
编辑:这里完整的代码片段完全使用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 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 newThing() {
return (T) new B();
}
public static void main(String... _) {
A $a = F.newThing();
// I $i = F.newThing();
System.out.println($a.methodA());
}
}