# 错误：模式类型 'java.lang.String' 不是选择器表达式类型 'java.lang.Integer' 的子类型

- **ID:** `java/pattern-matching-invalid-type-test`
- **领域:** java
- **类别:** compilation_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

在 switch 表达式或模式匹配语句中，模式类型必须是选择器表达式类型的子类型；否则模式永远无法匹配，导致编译时错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 17 | active | — | — |
| Java 19 | active | — | — |
| Java 21 | active | — | — |

## 解决方案

1. ```
   确保模式类型是选择器类型的子类型。例如，如果选择器是 `Number`，使用 `Integer i` 模式而不是 `String s`。修正后的代码：`switch (obj) { case Integer i -> ...; case String s -> ...; default -> ...; }`
   ```
2. ```
   使用密封接口或类来限制可能的类型，确保模式类型是子类型。
   ```
3. ```
   如果选择器类型是泛型类型，使用包含模式类型的通配符或类型参数，例如 `List<? extends Serializable>` 以允许 String 和 Integer 模式。
   ```

## 无效尝试

- **Change the selector expression to match the pattern type by casting.** — Casting changes the compile-time type but may cause ClassCastException at runtime; the pattern should be written to handle the actual type hierarchy. (80% 失败率)
- **Use `instanceof` in an if-else chain instead of switch.** — While this avoids the compile error, it doesn't leverage pattern matching's exhaustiveness and conciseness, and may reduce code readability. (50% 失败率)
- **Add a default case with a cast pattern.** — The default case does not resolve the type mismatch; the pattern type must be a subtype of the selector type at compile time. (90% 失败率)
