將泛型引數繫結到多個型別

通用引數也可以使用 T extends Type1 & Type2 & ... 語法繫結到多個型別。

假設你要建立一個類,其 Generic 型別應該同時實現 FlushableCloseable,你可以編寫

class ExampleClass<T extends Flushable & Closeable> {
}

現在,ExampleClass 只接受通用引數,型別同時實現 Flushable Closeable

ExampleClass<BufferedWriter> arg1; // Works because BufferedWriter implements both Flushable and Closeable

ExampleClass<Console> arg4; // Does NOT work because Console only implements Flushable
ExampleClass<ZipFile> arg5; // Does NOT work because ZipFile only implements Closeable

ExampleClass<Flushable> arg2; // Does NOT work because Closeable bound is not satisfied.
ExampleClass<Closeable> arg3; // Does NOT work because Flushable bound is not satisfied.

類方法可以選擇將泛型型別引數推斷為 CloseableFlushable

class ExampleClass<T extends Flushable & Closeable> {
    /* Assign it to a valid type as you want. */
    public void test (T param) {
        Flushable arg1 = param; // Works
        Closeable arg2 = param; // Works too.
    }

    /* You can even invoke the methods of any valid type directly. */
    public void test2 (T param) {
        param.flush(); // Method of Flushable called on T and works fine.
        param.close(); // Method of Closeable called on T and works fine too.
    }
}

注意:

你不能使用 OR|)子句將泛型引數繫結到任一型別。僅支援 AND&)子句。泛型型別只能擴充套件一個類和許多介面。類必須放在列表的開頭。