将泛型参数绑定到多个类型
通用参数也可以使用 T extends Type1 & Type2 & ...
语法绑定到多个类型。
假设你要创建一个类,其 Generic 类型应该同时实现 Flushable
和 Closeable
,你可以编写
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.
类方法可以选择将泛型类型参数推断为 Closeable
或 Flushable
。
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 (&
)子句。泛型类型只能扩展一个类和许多接口。类必须放在列表的开头。