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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)