java15比java14多了什么新特性
时间: 2024-01-19 14:04:56 浏览: 39
Java 15相比Java 14新增了一些新特性,以下是其中几个:
1. 隐藏类
Java 15中,引入了隐藏类(Hidden Classes)的概念,可以在不暴露类名的情况下创建类并实例化对象。这可以提高安全性并减少命名冲突。下面是一个例子:
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello, World!");
}
}
public class Main {
public static void main(String[] args) throws Exception {
var myRunnableClass = Class.forName("MyRunnable");
var myRunnableConstructor = myRunnableClass.getDeclaredConstructor();
myRunnableConstructor.setAccessible(true);
var myRunnable = (Runnable) myRunnableConstructor.newInstance();
myRunnable.run();
}
}
```
2. Records的增强
Java 15中,对Records进行了增强,支持使用“with”方法来创建新的对象,以及支持使用“equals”和“hashCode”方法进行比较。下面是一个例子:
```java
public record Person(String name, int age) {
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
public Person withName(String name) {
return new Person(name, age);
}
}
Person p1 = new Person("John", 30);
Person p2 = p1.withName("Jane");
System.out.println(p1.equals(p2)); // 输出 "false"
```
3. Text Blocks的增强
Java 15中,对Text Blocks进行了增强,支持使用“\”来转义换行符、支持使用嵌入式表达式以及支持使用“stripIndent”方法去除首尾空白符。下面是一个例子:
```java
String html = """
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>%s</p>
</body>
</html>
""".formatted("Hello, World!", "Hello, World!", "Lorem ipsum");
System.out.println(html.stripIndent());
```
以上就是Java 15的一些新特性。