Example: Usinginstanceof with Primitive Types in Java 22
Object value = 42;
if (value instanceof Integer i) {
System.out.println("Integer value: " + i);
}
Example: Using switch with Primitive Type Patterns in Java 22
Object value = 3.14;
String result = switch (value) {
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
default -> "Unknown type";
};
System.out.println(result);
Java 24 的增强功能:
该功能在 Java SE 23 中首次预览,本版本对其进行了重新预览。Java SE 23 与此版本之间没有变化。Java 24 将模式匹配扩展到包括所有模式上下文中的基元类型,如 instanceof 操作符和 switch 表达式及语句。这一增强功能使代码在处理对象和基元类型时更加简洁易读。instanceof 操作符和 switch 表达式及语句已扩展到可处理所有基元类型。
Example: Using instanceof with Primitive Types
int value = 42;
if (value instanceof int) { // Possible with Java 24
System.out.println("Integer value: " + i);
}
int value = 10; if (value instanceof int i && i > 5) { // Possible with Java 24 System.out.println("Value is an integer greater than 5"); }
Example: Using switch with Primitive Type Patterns
int status = 2;
String message = switch (status) {
case 0 -> "OK";
case 1 -> "Warning";
case 2 -> "Error";
case int i -> "Unknown status: " + i;
};
System.out.println(message);
double value = 3.14;
switch (value) {
case int i -> System.out.println("value is an integer");
case double d -> System.out.println("value is a double"); // Not possible before Java 24
default -> System.out.println("value is something else");}double d = 3.14; switch (d) {
case 3.14 -> System.out.println("Value is PI");
case 2.71 -> System.out.println("Value is Euler's number");
default -> System.out.println("Value is not a recognized constant");}
float rating = 0.0f;
switch (rating) {
case 0f -> System.out.println("0 stars");
case 2.5f -> System.out.println("Average");
case 5f -> System.out.println("Best");
default -> System.out.println("Invalid rating");
}
import module java.base;
public class BaseModuleExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
System.out.println("List created: " + list);
}
}
// Java program using classes from java.base
public class BaseExample {
public static void main(String[] args) {
String message = "Hello, Java!";
System.out.println(message.toUpperCase());
}
}
如果一个模块 A 需要 java.se,而另一个模块 B 需要 A,那么 B 也可以传递地访问 java.base。
module-info.java for moduleA
module moduleA {
requires java.se;
}
module-info.java for moduleB
module moduleB {
requires moduleA; // No need to explicitly require java.base
}
尽管模块 B 并不直接需要 java.base,但它仍然可以访问 java.base 中的类,因为模块 A 需要 java.se,而 java.se 过渡性地需要 java.base。
要点:
java.base 总是可用的,不需要明确需要。
java.se 是一个伞状模块,它需要多个模块,包括 java.base。
当您需要 java.se 时,您将自动访问 java.base 和所有标准 Java SE 模块。
传递依赖关系意味着,如果模块 A 需要 java.se,那么模块 B(需要模块 A)也能访问 java.base,而无需明确要求。
示例: 导入各种模块
import module java.util;
import module java.base;
import module java.sql;
import java.util.Date;
public class ModuleImportConflictExample {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Date: " + date);
List<String> list = new ArrayList<>();
System.out.println("Module import works!");
}
}
Stream 流收集器 (JEP-485)
Stream 流 API 为处理数据流提供了一组内置的中间操作(如 map、filter 和 flatMap)。这些操作虽然功能强大,但在需要进行更复杂的转换时可能会受到限制,往往导致开发人员编写自定义收集器或采用不那么优雅的解决方案。
import java.lang.ScopedValue;
import java.lang.ScopedValue.Carrier;
public class ScopedValueExample {
// Define a ScopedValue
private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();
public static void main(String[] args) {
// Create a carrier for the scoped value
Carrier carrier = ScopedValue.where(USER_ID, "user123");
// Run a task within the scope of the carrier
carrier.run(() -> {
// Access the scoped value within the scope
System.out.println("User ID: " + USER_ID.get());
performTask();
});
}
private static void performTask() {
// Access the scoped value in a nested method
System.out.println("Performing task for User ID: " + USER_ID.get());
}
}
向量 API 允许开发人员表达向量计算,这些计算可在运行时编译为所支持 CPU 架构上的最佳向量指令,从而实现优于同等标量计算的性能。
示例:矢量加法 矢量加法
VectorSpecies<Float> SPECIES = FloatVector.SPECIES_PREFERRED;
float[] a = {1.0f, 2.0f, 3.0f, 4.0f};
float[] b = {5.0f, 6.0f, 7.0f, 8.0f};
float[] c = new float[4];
for (int i = 0; i < a.length; i += SPECIES.length()) {
var va = FloatVector.fromArray(SPECIES, a, i);
var vb = FloatVector.fromArray(SPECIES, b, i);
var vc = va.add(vb);
vc.intoArray(c, i);
}
ML-KEM 是一种密钥封装机制,允许双方通过不安全的通信信道安全地建立共享秘密。然后,该共享秘密可与对称密钥加密算法一起用于加密和验证等任务。ML-KEM 的设计目的是安全抵御潜在的量子计算攻击,美国国家标准与技术研究院(NIST)已在 FIPS 203 中将其标准化。
在 Java 24 中使用 ML-KEM:
Java 24 为 ML-KEM 提供了 KeyPairGenerator、KEM 和 KeyFactory API 的实现,支持 FIPS 203 中定义的参数集 ML-KEM-512、ML-KEM-768 和 ML-KEM-1024。下面介绍如何在 Java 应用程序中使用 ML-KEM:
生成 ML-KEM 密钥对:
首先,使用 ML-KEM 的 KeyPairGenerator 生成密钥对:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.NamedParameterSpec;
public class MLKEMExample {
public static void main(String[] args) throws Exception {
// Initialize the KeyPairGenerator with the ML-KEM algorithm
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ML-KEM");
// Specify the parameter set; ML-KEM-512 is used here
keyPairGenerator.initialize(new NamedParameterSpec("ML-KEM-512"));
// Generate the key pair
KeyPair keyPair = keyPairGenerator.generateKeyPair();
System.out.println("ML-KEM Key Pair generated successfully.");
// The public and private keys can now be used for encapsulation and decapsulation
}
}
封装秘钥(发送方视角):
发送方使用接收方的公开密钥封装密钥:
import javax.crypto.KEM;
import javax.crypto.SecretKey;
// Assuming 'publicKey' is the recipient's ML-KEM public key
KEM kem = KEM.getInstance("ML-KEM");
KEM.Encapsulator encapsulator = kem.encapsulator(publicKey);
// Encapsulate the secret key
KEM.Encapsulated encapsulated = encapsulator.encapsulate();
// Retrieve the encapsulated message to send to the recipient
byte[] encapsulation = encapsulated.getEncapsulation();
// The sender's copy of the secret key
SecretKey secretKeySender = encapsulated.getKey();
System.out.println("Secret key encapsulated successfully.");
解封装秘钥(接收方视角):
接收方使用自己的私人密钥对收到的封装信息进行解封装:
import javax.crypto.KEM;
import javax.crypto.SecretKey;
// Assuming 'privateKey' is the recipient's ML-KEM private key
KEM kem = KEM.getInstance("ML-KEM");
KEM.Decapsulator decapsulator = kem.decapsulator(privateKey);
// Decapsulate the secret key using the received encapsulation
SecretKey secretKeyReceiver = decapsulator.decapsulate(encapsulation);
System.out.println("Secret key decapsulated successfully.");
你对本文的反应是: