将方法的返回值声明为公共超类型

时间:2018-10-12 21:03:08

标签: java generics

假设我有STU这三种类型,其中S是TU的最特定的通用超类型。我可以让用户明确声明:

class Foo<S, T extends S, U extends S>
{
    public S choose(T t, U u);  // chooses either t or u based on some criteria

    ...
}

有什么方法可以自动推断S吗?

class Foo<T, U>
{
    public ???? choose(T t, U u);  // chooses either t or u based on some criteria

    ...
}

1 个答案:

答案 0 :(得分:1)

尝试使用通用方法而不是通用类。

public class Main {
    static final Random random = new Random();

    public static void main(String... args) {
        Bar bar = choose(new Baz(), new Qux());
    }

    public static <S, T extends S, U extends S> S choose(T one, U two) {
        return random.nextBoolean() ? one : two;
    }

    interface Foo{}
    interface Bar extends Foo{}
    static class Baz implements Bar{}
    static class Qux implements Bar{}
}