You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Java的Pattern-Matching switch中使用Class<?>进行匹配?

问题原因

你的写法没有正确使用Pattern Matching for switch特性,属于语法使用错误,和特性本身的支持性无关。
你原来的switch写法依然沿用了旧版本的常量case逻辑,firstParameter.getType()返回的是Class<?>类型,编译器对通配符类型做捕获转换后,会认为Class<Integer>和捕获后的Class<CAP#1>类型不兼容,所以直接报类型转换错误。
而if判断没有switch的常量类型兼容校验规则,所以可以正常运行。

正确写法

你需要使用模式匹配的类型模式+守卫条件来实现同等逻辑:

Method firstMethod = BitSet.class.getDeclaredMethods()[0];
Parameter firstParameter = firstMethod.getParameters()[0];
switch (firstParameter.getType()) {
    case Class<?> c when c == Integer.class -> System.out.println("Integer");
    case Class<?> c when c == int.class -> System.out.println("int");
    default -> System.out.println("other");
}

内容的提问来源于stack exchange,提问作者yoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:36:03