Java实例of模式匹配怎么用

wen java案例 2

Java 实例of模式匹配(Pattern Matching for instanceof)使用指南

Java 16 正式引入了 instanceof 模式匹配功能,它简化了类型检查和类型转换的写法。

Java实例of模式匹配怎么用

基本语法

// 传统写法
if (obj instanceof String) {
    String str = (String) obj;
    System.out.println(str.length());
}
// 模式匹配写法(Java 16+)
if (obj instanceof String str) {
    System.out.println(str.length());
}

核心特点

变量绑定

自动将对象转换为匹配的类型并绑定到变量:

public void process(Object obj) {
    if (obj instanceof String s) {
        System.out.println("字符串长度: " + s.length());
    } else if (obj instanceof Integer i) {
        System.out.println("整数值: " + (i * 2));
    } else if (obj instanceof List<?> list) {
        System.out.println("列表大小: " + list.size());
    }
}

条件判断中的使用

// 可以结合 && 使用
if (obj instanceof String s && s.length() > 5) {
    System.out.println("长字符串: " + s);
}
// 注意:不能与 || 直接使用
// 错误示例:
// if (obj instanceof String s || s.length() > 5) { } // 编译错误

嵌套使用

class Shape { }
class Circle extends Shape { 
    double radius;
    Circle(double radius) { this.radius = radius; }
}
class Rectangle extends Shape {
    double width, height;
    Rectangle(double w, double h) { this.width = w; this.height = h; }
}
public void printArea(Shape shape) {
    if (shape instanceof Circle c) {
        System.out.println("圆面积: " + Math.PI * c.radius * c.radius);
    } else if (shape instanceof Rectangle r) {
        System.out.println("矩形面积: " + r.width * r.height);
    }
}

在 switch 表达式中使用(Java 17+)

public String describe(Object obj) {
    return switch (obj) {
        case Integer i -> "整数: " + i;
        case String s -> "字符串: " + s;
        case Long l -> "长整数: " + l;
        case null -> "空值";
        default -> "未知类型";
    };
}

实际应用示例

示例1:简化 equals() 方法

public class Person {
    private String name;
    private int age;
    @Override
    public boolean equals(Object obj) {
        // 传统写法
        // if (obj instanceof Person) {
        //     Person other = (Person) obj;
        //     return name.equals(other.name) && age == other.age;
        // }
        // return false;
        // 模式匹配写法
        return obj instanceof Person other 
               && name.equals(other.name) 
               && age == other.age;
    }
}

示例2:处理不同类型的数据

import java.util.*;
public class DataProcessor {
    public String processData(Object data) {
        // 传统写法
        // if (data instanceof Map) {
        //     Map<String, Object> map = (Map<String, Object>) data;
        //     return "Map with " + map.size() + " entries";
        // } else if (data instanceof List) {
        //     List<?> list = (List<?>) data;
        //     return "List with " + list.size() + " items";
        // }
        // 模式匹配写法
        if (data instanceof Map<?, ?> map) {
            return "Map with " + map.size() + " entries";
        } else if (data instanceof Collection<?> coll) {
            return "Collection with " + coll.size() + " items";
        } else if (data instanceof String s && !s.isEmpty()) {
            return "String: '" + s + "'";
        }
        return "Unknown data type";
    }
}

注意事项

  1. 变量作用域:模式变量只在匹配成功的代码块中可用
  2. 不能与 || 混用:模式变量不能在 || 连接的表达式中使用
  3. 命名冲突:避免与外部变量同名
  4. 性能优化:编译器会优化模式匹配,性能优于传统写法

兼容性要求

  • 需要 Java 16 或更高版本
  • 需要在 pom.xml 中配置:
    <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
    </properties>

模式匹配让代码更简洁、易读,减少了类型转换的样板代码。

抱歉,评论功能暂时关闭!