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

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>());
    }
}


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

最佳答案

声明TU是从R开始的。

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

08-27 05:32