Java泛型里的Intersection Type
Intersection Type
交叉类型,语法:Type1 & Type2
示例写法
public class MyClass {
public void hello() {
System.out.println("hello");
}
}
interface MyInteface {
// ...
default void world() {
System.out.println(" world");
}
}
interface MyInteface2 {
// ...
default void intersection() {
System.out.println(" intersection");
}
}
public class MyIntersection extends MyClass implements MyInteface, MyInteface2 {
// ...
}
/**
* 泛型里的交叉类型,只能用于类上、方法上的泛型声明,实例化时不能使用&
*
* @param <T>
*/
class MyCat<T extends MyClass & MyInteface & MyInteface2> {
T t;
public MyCat(T t) {
this.t = t;
}
T getIntersection() {
return this.t;
}
}
@Test
void testIntersection2() {
MyIntersection myIntersection = new MyIntersection();
MyCat<MyIntersection> myCat = new MyCat<>(myIntersection); // OK
myCat.getIntersection().hello();
myCat.getIntersection().world();
myCat.getIntersection().intersection();
MyCat<MyClass> myCat2 = new MyCat<>(); // compile error
MyCat<MyInteface> myCat3 = new MyCat<>(); // compile error
}
MyCat<T extends MyClass & MyInteface>即申明一个带泛型的交叉类型,T extends MyClass & MyInteface含义是:T既要是MyClass的子类,也要是MyInteface的子类,T同时拥有MyClass、MyInteface的所有行为。
这看起来是取MyClass、MyInteface的并集,为啥叫intersection type?因为T不是为了说明T有哪些行为,而是为了表达T的可选类型被限定在得兼具两种类型,T的可选类型范围变小,符合数学里的交叉(交集)的含义。
Java函数式编程里的交叉类型
可用于只要入参和返回类型匹配一样的函数就可以做cast类型转换
Serializable ser = (Serializable & Calculator) Long::sum;
System.out.println(ser instanceof Serializable);
System.out.println(ser instanceof Calculator);
Runnable job = (Runnable & Serializable) () -> System.out.println("Hello");
Class<?>[] interfaces = job.getClass().getInterfaces();
for (Class<?> i : interfaces) {
System.out.println(i.getSimpleName());
}
输出:
true
true
Runnable
Serializable

浙公网安备 33010602011771号