使用instanceof模式匹配遇困惑错误:表达式类型Triple是模式类型Triple的子类型
Java 19自定义Record模式匹配编译错误问题
使用Java 19时,在自定义的Triple Record上执行简单模式匹配操作,触发了编译错误。以下是可复现问题的最简代码:
public class ExpressionTypeIsASubsetOfPatternType { public record Triple(int a, int b, int c) {} public static void main(String[] args) { System.out.println("Java Version = " + System.getProperty("java.version")); final Triple input = new Triple(1, 2, 3); if (input instanceof Triple t) { System.out.println("Made it here"); } } }
编译运行时的错误信息:
$ java ExpressionTypeIsASubsetOfPatternType.java ExpressionTypeIsASubsetOfPatternType.java:15: error: expression type Triple is a subtype of pattern type Triple if (input instanceof Triple t) ^ 1 error error: compilation failed
使用的Java版本信息:
$ java --version openjdk 19 2022-09-20 OpenJDK Runtime Environment (build 19+36-2238) OpenJDK 64-Bit Server VM (build 19+36-2238, mixed mode, sharing)
$ javac --version javac 19
错误原因与解决方法
这个错误的核心是冗余类型检查:变量input的静态类型已经是Triple,instanceof Triple t的检查完全没有必要——input不可能不是Triple实例,编译器因此禁止这种无意义的代码。
有两种解决方式:
- 直接使用
input变量,移除冗余的instanceof判断:System.out.println("Made it here"); - 如果目标是对Record进行解构模式匹配(提取内部字段),使用Record解构语法:
if (input instanceof Triple(int a, int b, int c)) { System.out.println("a: " + a + ", b: " + b + ", c: " + c); }
内容的提问来源于stack exchange,提问作者davidalayachew
相关产品推荐
相关产品推荐

