300 秒快速了解 Java 9 - 16 新特性
肉眼品世界
共 8729字,需浏览 18分钟
·
2021-09-01 15:00
Java 9(2017年9月)
接口里可以添加私有接口
public interface TestInterface {
default void wrapMethod(){
innerMethod();
}
private void innerMethod(){
System.out.println("");
}
}
<>
,可以自动推断泛型的类型:List<Integer> numbers = new ArrayList<>();
List<Integer> numbers = new ArrayList<>() {
...
}
增强的 try-with-resources
try-with-resources
的支持,可以自动关闭资源:try (BufferedReader bufferReader = new BufferedReader(...)) {
return bufferReader.readLine();
}
try (BufferedReader bufferReader0 = new BufferedReader(...);
BufferedReader bufferReader1 = new BufferedReader(...)) {
return bufferReader0.readLine();
}
BufferedReader bufferReader0 = new BufferedReader(...);
BufferedReader bufferReader1 = new BufferedReader(...);
try (bufferReader0; bufferReader1) {
System.out.println(br1.readLine() + br2.readLine());
}
Java 10(2018年3月)
局部变量的自动类型推断(var)
var
,它可以自动推断局部变量的类型,以后再也不用写类型了,也不用靠 lombok 的 var
注解增强了var message = "Hello, Java 10";
Java 11(2018年9月)
Lambda 中的自动类型推断(var)
var
这个自动类型推断的变量,通过 var 变量还可以增加额外的注解:List<String> languages = Arrays.asList("Java", "Groovy");
String language = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assertThat(language).isEqualTo("Java, Groovy");
javac + java 命令一把梭
$ java HelloWorld.java
Hello Java 11!
Java 12(2019年3月)
更简洁的 switch 语法
switch
语法还是比较啰嗦的,如果多个值走一个逻辑需要写多个 case
:DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
String typeOfDay = "";
switch (dayOfWeek) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
typeOfDay = "Working Day";
break;
case SATURDAY:
case SUNDAY:
typeOfDay = "Day Off";
}
typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> "Day Off";
};
instanceof
判断一下,然后再强转为该类型处理:Object obj = "Hello Java 12!";
if (obj instanceof String) {
String s = (String) obj;
int length = s.length();
}
instanceof
支持直接类型转换了,不需要再来一次额外的强转:Object obj = "Hello Java 12!";
if (obj instanceof String str) {
int length = str.length();
}
Java 13(2019年9月)
switch 语法再增强
swtich
语法,但并不能在 ->
之后写复杂的逻辑,JAVA 12 带来了 swtich
更完美的体验,就像 lambda
一样,可以写逻辑,然后再返回:typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
// do sth...
yield "Working Day";
}
case SATURDAY, SUNDAY -> "Day Off";
};
String json = "{\"id\":\"1697301681936888\",\"nickname\":\"空无\",\"homepage\":\"https://juejin.cn/user/1697301681936888\"}";
String json = """
{
"id":"1697301681936888",
"nickname":"空无",
"homepage":"https://juejin.cn/user/1697301681936888"
}
""";
Java 14(2020年3月)
新增的 record 类型,干掉复杂的 POJO 类
record
public record UserDTO(String id,String nickname,String homepage) { };
public static void main( String[] args ){
UserDTO user = new UserDTO("1697301681936888","空无","https://juejin.cn/user/1697301681936888");
System.out.println(user.id);
System.out.println(user.nickname);
System.out.println(user.id);
}
更直观的 NullPointerException 提示
innerMap
为空呢,还是 effected
为空呢?Map<String,Map<String,Boolean>> wrapMap = new HashMap<>();
wrapMap.put("innerMap",new HashMap<>());
boolean effected = wrapMap.get("innerMap").get("effected");
// StackTrace:
Exception in thread "main" java.lang.NullPointerException
at org.example.App.main(App.java:50)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.Map.get(Object)" is null
at org.example.App.main(App.java:50)
effected
变量为空,再也不用困惑!// 分配 200B 堆外内存
MemorySegment memorySegment = MemorySegment.allocateNative(200);
// 用 ByteBuffer 分配,然后包装为 MemorySegment
MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
// MMAP 当然也可以
MemorySegment memorySegment = MemorySegment.mapFromPath(
Path.of("/tmp/memory.txt"), 200, FileChannel.MapMode.READ_WRITE);
// 获取堆外内存地址
MemoryAddress address = MemorySegment.allocateNative(100).baseAddress();
// 组合拳,堆外分配,堆外赋值
long value = 10;
MemoryAddress memoryAddress = MemorySegment.allocateNative(8).baseAddress();
// 获取句柄
VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
// 释放就这么简单,想想 DirectByteBuffer 的释放……多奇怪
memorySegment.close();
新增的 jpackage 打包工具,直接打包二进制程序,再也不用装 JRE 了
jpackage
打包工具,帮助你一键打包二进制程序包,终于不用乱折腾了Java 15(2020年9月)
ZGC 和 Shenandoah 两款垃圾回收器正式登陆
封闭(Sealed )类
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}
总结
看看时间,300 秒到了吗?
推荐阅读:
评论