Java主要版本新特性

发布于:2025-08-09 ⋅ 阅读:(20) ⋅ 点赞:(0)

Java主要版本新特性详解(Java 8 到 Java 21)

:截至2024年,Java最新LTS版本为21(2023年9月发布),Java 23尚未发布。以下将按版本顺序介绍核心特性,并提供代码对比示例。


一、Java 8 (2014年)

核心特性:Lambda表达式、Stream API、Optional类、新的日期时间API
代码对比示例

// 更新前:匿名内部类实现排序
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.compareTo(b);
    }
});

// 更新后:Lambda表达式
Collections.sort(names, (a, b) -> a.compareTo(b));
// 更新前:手动处理空指针
public String getUpperCaseName(User user) {
    if (user != null && user.getName() != null) {
        return user.getName().toUpperCase();
    }
    return null;
}

// 更新后:Optional类
public String getUpperCaseName(User user) {
    return Optional.ofNullable(user)
                   .map(User::getName)
                   .map(String::toUpperCase)
                   .orElse(null);
}
// 更新前:java.util.Date
Date date = new Date(2023, 1, 1); // 已过时,线程不安全

// 更新后:java.time.LocalDate
LocalDate date = LocalDate.of(2023, 1, 1); // 不可变,线程安全

二、Java 11 (2018年,LTS)

核心特性:局部变量类型推断(var)、HTTP Client API、String增强方法
代码对比示例

// 更新前:显式类型声明
String message = "Hello";
List<String> list = new ArrayList<>();

// 更新后:var关键字(局部变量)
var message = "Hello";
var list = new ArrayList<String>();
// 更新前:HttpURLConnection(繁琐)
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

// 更新后:HTTP Client(异步请求)
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://example.com"))
        .build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);
// String新增方法
"  ".isBlank();      // true(检测空白字符)
"Java\n11".lines().count();  // 2(按行分割)
"  hello  ".strip();  // "hello"(去除首尾空白)

三、Java 17 (2021年,LTS)

核心特性:密封类(Sealed Classes)、模式匹配、文本块
代码对比示例

// 密封类:限制继承关系
public sealed interface Shape permits Circle, Rectangle { }

public final class Circle implements Shape { }   // 明确许可的子类
public final class Rectangle implements Shape { }
// 更新前:类型检查与转换
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

// 更新后:模式匹配
if (obj instanceof String s) {
    System.out.println(s.length()); // 直接使用s
}
// 更新前:拼接多行字符串
String html = "<html>\n" +
              "  <body>\n" +
              "    <p>Hello</p>\n" +
              "  </body>\n" +
              "</html>";

// 更新后:文本块(Text Blocks)
String html = """
              <html>
                <body>
                  <p>Hello</p>
                </body>
              </html>
              """;

四、Java 21 (2023年,LTS)

核心特性:虚拟线程(Virtual Threads)、模式匹配switch、记录模式
代码对比示例

// 虚拟线程(轻量级线程)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(() -> System.out.println("Hello from virtual thread!"));
}
// 模式匹配switch
static String checkType(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case String s  -> "String: " + s;
        case null      -> "Null value";
        default        -> "Unknown type";
    };
}
// 记录模式(解构记录类)
record Point(int x, int y) {}

static void printSum(Object obj) {
    if (obj instanceof Point(int x, int y)) {  // 直接解构
        System.out.println(x + y);
    }
}

总结对比表

版本 关键特性 适用场景
Java 8 Lambda、Stream API 函数式编程、集合操作
Java 11 var、HTTP Client 简化代码、现代HTTP通信
Java 17 密封类、文本块 安全继承、多行文本处理
Java 21 虚拟线程、模式匹配switch 高并发、简化类型分支逻辑

建议:新项目推荐使用 Java 21(LTS),企业存量系统可评估升级至Java 17或11。

思维导图

Java主要版本新特性


网站公告

今日签到

点亮在社区的每一天
去签到