栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 8 后的新功能梳理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 8 后的新功能梳理

为什么要写这篇文章

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

让我们对比学习一下最新一版的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 biFunction = (a, b) -> a + b;
        BiFunction 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");
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683491.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号