jdk17的一些新特性
1、Switch语句得到增强
1.1 不需要再去写break
了(这种写法是jdk12增加的)
旧写法
String alias;
switch (name){
case "周瑜":
alias = "公瑾";
break;
case "徐庶":
alias = "元直";
break;
case "项羽":
alias = "西楚霸王";
break;
default:
alias = "未知";
break;
}
新写法
String name = "徐庶";
String alias = switch (name){
case "周瑜" -> "公瑾";
case "徐庶" -> "元直";
case "项羽" -> "西楚霸王";
default -> "未知";
};
1.2 多个case使用同一个break的,可以使用,
分隔即可(jdk17新增加的)
例如:
旧写法
switch (name){
case "周瑜":
case "徐庶":
country = "三国";
break;
case "项羽":
case "刘邦":
country = "汉朝";
break;
default:
country = "未知";
break;
}
新写法
String country = switch(sname){
case "徐庶","周瑜" -> "三国";
case "项羽","刘邦" -> "汉朝";
default -> "未知";
};
如果case里面有多行业务代码,则需要加一个大括号,并且用yield
关键字作为变量的返回值
例如:
String country = switch(sname){
case "徐庶","周瑜" -> "三国";
case "项羽","刘邦" -> {
System.out.println("这里是业务代码");
yield "汉朝";
}
default -> "未知";
};
1.3 增加了对变量类型的匹配(jdk17预览版)
例如:
public String testPatternMatchSwitch(Object o){
return switch (o){
case String s -> String.format("String s:%s",s);
case Integer i -> String.format("Integer i:%s",i);
case Boolean b -> String .format("Boolean b:%s",b);
case Long l -> String.format("Long l : %s",l);
case Float f -> String.format("Float f : %s",f);
case Double d -> String .format("Double d : %s",d);
case Byte b -> String.format("Byte b : %s",b);
default -> o.toString();
};
}
2. 增加了文本块
使用"""
文字内容"""
的形式
文本块是jdk15出现的,而jdk17增加了\
和\s
两个转义符
\
:去掉换行
\s
:一个空格
String html = """
<html>
<body>
<h1>Hello,World!</h1>
</body>
</html>
""";
3. 使用instanceof判断类型后,再次使用该对象无需强转(在jdk14预览版中首次添加,在jdk16正式增加)
例如:
Object o = 1;
if (o instanceof Integer i){
System.out.println(i.intValue());
}else if (o instanceof String s){
System.out.println(s.charAt(0));
}
4. sealed密封类
- jdk17新加的功能sealed,密封类,也可以叫限制继承类,通过permits关键词去限制子类的继承
- 被限制继承的子类,必须跟父类在同一个包内,而且需要加关键词final或者non-sealed
- final:最终类,无法再被子类继承
- non-sealed:可以被子类再继承
- sealed优缺点,更加的安全,更加的可控,更易于维护
举个例子:
1、首先创建一个Animal类,添加sealed关键字,使用permits关键字去指定可以继承的子类
public abstract sealed class Animal permits Dog,Cat{
}
2、然后创建一个Dog类,去继承Animal,Dog类无需被其他子类继承,所以使用final关键字
public final class Dog extends Animal{
}
3、再创建一个Cat类去继承Animal,Cat类需要被其他子类继承,所以使用non-sealed关键字
public non-sealed class Cat extends Animal{
}
4、如果使用没有被允许继承的子类去继承Animal,则会报错。
5. ZGC增强
ZGC 是一种基于 Region 的低延迟垃圾收集器
ZGC在jdk11的时候诞生,在jdk15的时候正式使用
ZGC的好吃是垃圾回收不卡顿,ZGC的STW<10ms,几乎感受不到
Java 17 引入了以下新特性:
卸载类:在不停机的情况下,卸载不需要的类,可以减少内存占用。
日志记录:提供了更丰富的日志记录选项,方便进行调试和性能分析。