簡體   English   中英

將方法的返回值聲明為常用超類型

[英]Declaring the return value of a method as the common supertype

假設我有三種類型, ST ,以及U其中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

    ...
}

嘗試使用泛型方法而不是泛型類。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM