假设我有S
,T
和U
这三种类型,其中S是T
和U
的最特定的通用超类型。我可以让用户明确声明:
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
...
}
答案 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{}
}