JDK 22 新特性详解
· 阅读需 8 分钟
Java 22 作为一个非长期支持版本(non-LTS),于2024年3月19日正式发布。这个版本继续改进了一些预览特性,并带来了一些新的改进。让我们一起来了解这些新特性。
1. 字符串模板(第二次预览)
字符串模板的改进版本:
public class StringTemplateDemo {
public static void main(String[] args) {
// 基本用法
String name = "张三";
int age = 25;
String info = STR."用户 \{name} 的年龄是 \{age}";
System.out.println(info);
// 使用 JSON 处理器
record Person(String name, int age, String city) {}
var person = new Person("李四", 30, "北京");
String json = JSON."""
{
"name": "\{person.name()}",
"age": \{person.age()},
"city": "\{person.city()}",
"timestamp": "\{java.time.LocalDateTime.now()}"
}
""";
System.out.println(json);
// 使用 SQL 处理器
String tableName = "users";
String condition = "active = 1";
int limit = 10;
String sql = SQL."""
SELECT *
FROM \{tableName}
WHERE \{condition}
LIMIT \{limit}
""";
System.out.println(sql);
// 使用 FMT 处理器进行格式化
double price = 12345.6789;
String formatted = FMT."价格:%.2f 元\{price}";
System.out.println(formatted);
// 嵌套模板
var items = List.of("苹果", "香蕉", "橙子");
String html = STR."""
<ul>
\{items.stream()
.map(item -> STR."<li>\{item}</li>")
.collect(Collectors.joining("\n "))}
</ul>
""";
System.out.println(html);
// 条件模板
boolean isAdmin = true;
String role = STR."用户角色:\{isAdmin ? "管理员" : "普通用户"}";
System.out.println(role);
// 使用自定义处理器
String log = LogTemplate."""
[%level] \{LocalDateTime.now()}: \{message}
""";
}
// 自定义模板处理器
static class LogTemplate {
public static String process(StringTemplate template) {
return template.interpolate()
.replace("%level", "INFO");
}
}
}
改进特性:
- 更多内置处理器
- 改进的语法支持
- 更好的性能
- 增强的类型安全