加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java泛型:有界类型参数中的多重继承

发布时间:2020-12-14 05:31:01 所属栏目:Java 来源:网络整理
导读:我即将创建一个创建一个类型为T的对象的工厂,它扩展了一个类A和另一个接口I.然而,T不能被知道.以下是最低声明: public class A { }public interface I { } 这是工厂方法: public class F { public static T extends A I T newThing() { /*...*/ }} 这汇编
我即将创建一个创建一个类型为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();

编译器抱怨:

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 extends A & I> 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 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的类型,然后你会返回它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读