Java 8 後的新功能梳理

Kwanwooo發表於2021-12-27

為什麼要寫這篇文章

經過了若干年的發展,Java逐步從java8升級為java11java17
讓我們對比學習一下最新一版的LTS版本和java8比起來讓程式碼簡化了多少。

  1. 文字塊(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);
    }
}
  1. 本地變數型別推斷(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;
    }
  1. 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();
                }
        );
    }
  1. 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("沒有這種動物的叫聲");
        }
    }
}
  1. record 類
// 傳統類
public record People(String name, int age) {
    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

相關文章