Java JDK 8 到 19 演升特性汇总
文章目录
一、版本roadmap图
官方地址
JDK8,JDK11,JDK17,JDK21是长期维护的版本。spring boot3最低支持JDK17。
二、版本与特性
JDK8 [2014-03-18]
1、语言新特性
1.1接口新增默认方法与静态方法:
Interface Default Method:For creating a default method in java interface, we need to use “default” keyword with the method signature.
Interface Static Method:interface static method is similar to default method except that we can’t override them in the implementation classes.
1.2 Functional Interfaces函数式接口
含有一个显式声明函数(抽象方法)的接口称为函数接口,注释@FunctionalInterface用作检查代码块,包package java.util.function,通常使用lambda expressions来实体化函数接口。
函数式接口:函数形接口 、供给形接口、消费型接口、判断型接口。
1.2 Lambda表达式
语法:( object str,…)[参数列表] ->[箭头符号] 代码块或表达式。
特性:Lambda 的类型是从使用 Lambda 的上下文推断出来的。上下文中 Lambda 表达式需要的类型称为目标类型(一个 Lambda表达式所在的类的类型。并且必须存在一个目标类型); 匿名、函数、传递、简洁。
Arrays.sort(new SysUser[5], (SysUser a, SysUser b) -> {
return a.getUserId().compareTo(b.getUserId());
});
1.3 方法引用
方法引用操作符“::”,左边是类名或者某个对象的引用,右边是方法名,有下面几种方式:
(1)对象(引用)::实例方法名 new SysUser()::getUserName
(2)类名::静态方法名 Function<Long, Long> f = Math::abs;
(3)类名::实例方法名 SysUser::getUserName
(4)类名::new SysUser::new
(5)类型[]::new Function<Integer, SysUser[]> funUsers = SysUser[]::new;
1.4 重复注解@Repeatable
重复注解机制,相同的注解可在同一地方声明多次.
@Repeatable(Annotations.class)
public @interface MyAnnotation {
String role();
}
public @interface Annotations {
MyAnnotation[] value();
}
public class RepeatAnnotationUseOldVersion {
@MyAnnotation(role="Admin")
@MyAnnotation(role="Manager")
public void doSomeThing(){
}
}
对比以前jdk8的注解实现:
public @interface MyAnnotation {
String role();
}
public @interface Annotations {
MyAnnotation[] value();
}
public class RepeatAnnotationUseOldVersion {
@Annotations({
@MyAnnotation(role="Admin"),@MyAnnotation(role="Manager")})
public void doSomeThing(