基于 Java 17 LTS 的 實用示例
以下是基于 Java 17 LTS 的 30 個實用示例,涵蓋語言新特性、API 改進及常見場景。所有代碼均兼容 Java 17 語法規范。
文本塊(Text Blocks)
String json = """{"name": "Java 17","type": "LTS","features": ["Text Blocks", "Pattern Matching"]}
""";
System.out.println(json);
多行字符串無需轉義符,保留原始格式。
Switch 表達式
String day = "MONDAY";
int numLetters = switch (day) {case "MONDAY", "FRIDAY" -> 6;case "TUESDAY" -> 7;default -> day.length();
};
System.out.println(numLetters); // 輸出: 6
支持箭頭語法和返回值,避免 break
語句。
模式匹配(instanceof)
Object obj = "Java 17";
if (obj instanceof String s && s.length() > 5) {System.out.println(s.toUpperCase()); // 輸出: JAVA 17
}
直接類型轉換與變量綁定。
密封類(Sealed Classes)
public sealed interface Shape permits Circle, Rectangle {double area();
}public final class Circle implements Shape {private double radius;@Override public double area() { return Math.PI * radius * radius; }
}
限制可繼承的子類范圍。
Record 類
record Point(int x, int y) {}
Point p = new Point(10, 20);
System.out.println(p.x()); // 輸出: 10
自動生成 equals()
、hashCode()
和 toString()
。
Stream API 增強
List<String> list = List.of("a", "b", "c");
List<String> filtered = list.stream().filter(s -> s.startsWith("a")).toList(); // 直接轉為不可變列表
Stream.toList()
替代 collect(Collectors.toList())
。
日期時間 API
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(date.format(formatter));
線程安全的日期格式化。
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);
異步發送 HTTP 請求。
更多示例
-
Null檢查
String str = null; System.out.println(Objects.requireNonNullElse(str, "default"));
-
集合工廠方法
Set<String> set = Set.