亲宝软件园·资讯

展开

Java8后的新功能

Kwanwooo 人气:0

为什么要写这篇文章

经过了若干年的发展,Java逐步从java8升级为java11,java17。

让我们对比学习一下最新一版的LTS版本和java8比起来让代码简化了多少。

文本块(Text Blocks)

这个写法有些类似于 javascript、 Lua等脚本语言。方便识别html、json等格式复杂的字符串。

public class StringTest {
    public static void main(String[] args) throws Exception {
         // 传统写法
        String json =
                "{\n" +
                "    \"key\":\"a\",\n" +
                "    \"value\":\"b\"\n" +
                "}";
        // 优化后写法
        String json2 = """
                {
                    "key":"a",
                    "value":"b"
                }
                """;
        // 返回为 true
        System.out.println(json == json2);
    }
}

本地变量类型推断(Local Variable Type Inference)

这一点也是在一些脚本语言中常见的,类似于 var 表示变量,val 表示常量。

    public static void main(String[] args) throws Exception {
        //集合
        // immutable map build
        var map = Map.of(
                "cat", "猫",
                "dog", "狗",
                "fish", "鱼");
        // immutable set build
        var set = Set.of("1", "2", "3");
        // immutable list build
        var list = List.of(1, 2, 3, 4, 5);

        // 循环语句
        for (var i = 1; i < list.size(); i++) {
            System.out.println(i);
        }
        for (var i : list) {
            System.out.println(i);
        }

        // 异常
        try (var in = new ByteArrayInputStream("123".getBytes())) {
            System.out.println(new String(in.readAllBytes(), "utf-8"));
        } catch (Exception e) {
            System.out.println(e);
        }

        // lambda 表达式 意思相同
        BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
        BiFunction<Integer, Integer, Integer> biFunction2 = (var a, var b) -> a + b;
    }

switch

    public static void main(String[] args) throws Exception {
        var eating = Eating.BREAKFAST;
        String eatingZnString = "";
        // 传统写法
        switch (eating) {
            case BREAKFAST:
            case LUNCH:
                eatingZnString = "早午饭";
                break;
            case DINNER:
                eatingZnString = "晚饭";
                break;
            default:
                throw new Exception();
        }
        System.out.println(eatingZnString);

        // 优化后写法
        System.out.println(
                switch (eating) {
                    case BREAKFAST,LUNCH -> "早午饭";
                    case DINNER -> "晚饭";
                    default -> throw new Exception();
                }
        );
    }

instance of操作符的模式匹配(Pattern Matching for the instanceof Operator)

interface Animal {}

class Cat implements Animal {
    public void mew() {
        System.out.println("喵");
    }
}

class Dog implements Animal {
    public void woof() {
        System.out.println("汪");
    }
}

public class Test {
    // 传统写法
    public static void sounds(Animal animal) {
        if (animal instanceof Cat) {
            Cat cat = (Cat) animal;
            cat.mew();
        } else if (animal instanceof Dog) {
            Dog dog = (Dog) animal;
            dog.woof();
        } else {
            throw new IllegalArgumentException("没有这种动物的叫声");
        }
    }
    
    // 优化写法
    public static void betterSounds(Animal animal) {
        if (animal instanceof Cat cat) {
            cat.mew();
        } else if (animal instanceof Dog dog) {
            dog.woof();
        } else {
            throw new IllegalArgumentException("没有这种动物的叫声");
        }
    }
}

record 类

// 传统类
public final class People {
    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String name() {
        return this.name;
    }

    public int age() {
        return this.age;
    }
    public boolean equals(People people) {...}
    public int hashCode() {...}
    public String toString() {...}
}

// 优化后的类
public record People (String name, int age){ 
    
}

// 更多用法
public record People (String name, int age){
    // 静态字段
    static int teenageAge;

    // 静态初始化
    static {
        teenageAge = 17;
    }
    // 静态方法
    public static People buildTeenage(String name) {
        return new People(name , teenageAge);
    }

    // 优化后的构造方法
    public People {
        if (age < 0) {
            throw new IllegalArgumentException("年龄不能小于0");
        }
    }
}

参考文档

Java Language Updates

总结

加载全部内容

相关教程
猜你喜欢
用户评论