能否在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
相关产品推荐
相关产品推荐

