Java从8到21的语言新特性
try-with-resource可以使用既有的变量
// java 9 之前
try (InputStream is = Files.newInputStream(Paths.get("1111"))) {
// do something
}
// java 9 之后可以这样了
InputStream is = Files.newInputStream(Paths.get("1111"));
try (is) {
// do something
}
钻石操作符扩展
现在钻石操作符可以和匿名类一起使用:
FooClass<Integer> fc = new FooClass<>(1) {
};
FooClass<? extends Integer> fc0 = new FooClass<>(1) {
};
FooClass<?> fc1 = new FooClass<>(1) {
};
接口私有方法
接口可以包含私有方法,主要用于防止默认方法过长:
interface InterfaceWithPrivateMethods {
private static String staticPrivate() {
return "static private";
}
private String instancePrivate() {
return "instance private";
}
default void check() {
String result = staticPrivate();
InterfaceWithPrivateMethods pvt = new InterfaceWithPrivateMethods() {
};
result = pvt.instancePrivate();
}
}
类型推断var
类型推断仅可用于局部变量和lambda表达式中:
var x = 1;
switch表达式
在此之前:
// 之前
boolean isTodayHoliday;
switch (day) {
case "MONDAY":
case "TUESDAY":
case "WEDNESDAY":
case "THURSDAY":
case "FRIDAY":
isTodayHoliday = false;
break;
case "SATURDAY":
case "SUNDAY":
isTodayHoliday = true;
break;
default:
throw new IllegalArgumentException("What's a " + day);
}
// 从14开始
boolean isTodayHoliday = switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
case "SATURDAY", "SUNDAY" -> true;
default -> throw new IllegalArgumentException("What's a " + day);
};
// 从17开始
static record Human (String name, int age, String profession) {}
public String checkObject(Object obj) {
return switch (obj) {
case Human h -> "Name: %s, age: %s and profession: %s".formatted(h.name(), h.age(), h.profession());
case Circle c -> "This is a circle";
case Shape s -> "It is just a shape";
case null -> "It is null";
default -> "It is an object";
};
}
public String checkShape(Shape shape) {
return switch (shape) {
case Triangle t && (t.getNumberOfSides() != 3) -> "This is a weird triangle";
case Circle c && (c.getNumberOfSides() != 0) -> "This is a weird circle";
default -> "Just a normal shape";
};
}
字符块
String multiline = """
A quick brown fox jumps over a lazy dog; \
the lazy dog howls loudly.""";
字符串模板
String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
return STR
. "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}
// 或者字串块
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
return STR
. """
{
"feelsLike": "\{ feelsLike }",
"temperature": "\{ temperature }",
"unit": "\{ unit }"
}
""" ;
}
也可以带格式化的:
String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
return FMT
. """
{
"feelsLike": "%1s\{ feelsLike }",
"temperature": "%2.2f\{ temperature }",
"unit": "%1s\{ unit }"
}
""" ;
}
参见baeldung的说明。
模式匹配 instanceof
可以在instanceof
判断的同时声明新的变量了:
if (obj instanceof String str) {
int len = str.length();
}
Records
public record User(int id, String password) { };
Sealed Classes (JEP 360)
只允许特定的类继承,配合模式匹配会很好用,即可以确定匹配到所有已知的类型:
public abstract sealed class Person permits Employee, Manager {
}
public final class Employee extends Person {
}
public non-sealed class Manager extends Person {
}
参考:
标签:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)