java 泛型多重限制_Java泛型:有界类型参数中的多重继承

我即将创建一个创建一个类型为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());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值