首页 > 解决方案 > 受其他两个泛型类型约束的泛型类型限制

问题描述

我试图使方法的泛型返回类型受参数的两个泛型类型的约束,从某种意义上说,它应该是两者中最低的常见类型。例如:

class Scratch {

    static <T, U, R /*additional restrictions*/> R getLowestCommon(T t, U u) {
        return null;
    }

    public static void main(String[] args) {
        Object o = getLowestCommon("", 1);
        CharSequence s = getLowestCommon("", new StringBuilder());
        Number n = getLowestCommon(1L, 2D);
        Collection<Integer> c = getLowestCommon(new ArrayList<Integer>(), new HashSet<Integer>());
        // this should give an error because ArrayList's and HashSet's lowest common supertype is Collection
        List<Integer> l = getLowestCommon(new ArrayList<Integer>(), new HashSet<Integer>());
    }
}

我知道对交集类型的这种限制,但是有什么方法可以在 Java 中进行这种编译时限制吗?

标签: javagenerics

解决方案


那么从 R 中声明TU扩展呢?

static <T extends R, U extends R, R > R getLowestCommon(T t, U u)

推荐阅读