[英]Declaring the return value of a method as the common supertype
假設我有三種類型, 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
...
}
嘗試使用泛型方法而不是泛型類。
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{}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.