当前位置:首页>java>Java 25:4个能够减少冗余代码的强大功能

Java 25:4个能够减少冗余代码的强大功能

  • 2026-10-10 19:33:29
Java 25:4个能够减少冗余代码的强大功能

主方法简化

  • 在 Java 25 之前,你总是需要一个包含 public static void main(String[] args) 方法的公共类,以及大量的样板代码。

  • 在 Java 25 中,你可以编写简洁的源文件,并使用实例 main() 方法(即非静态方法)。

  • 你还可以使用诸如 IO.println() 和 readln() 之类的辅助 I/O 方法来简化控制台输入输出。

在 Java 25 之前

import java.util.Scanner;

publicclassHelloWorld{
publicstaticvoidmain(String[] args){
// Create a Scanner for input
        Scanner scanner = new Scanner(System.in);

// Ask for name
        System.out.println("What is your name?");
        String name = scanner.nextLine();

// Greet the user
        System.out.println("Hello, " + name + "!");

// Close the scanner
        scanner.close();
    }
}

在 Java 25 之后

void main() {
    IO.println("What is your name?");
String name = IO.readln();
    IO.println("Hello, " + name + "!");
}

简化的 I/O API

  • Java 25 引入了辅助控制台 I/O 方法,因此您不必总是编写System.out.println(…)或使用Scanner来进行简单的读取操作。

  • 使用IO.println()和IO.readln()(及其重载)更加简洁。这与紧凑的源/实例主函数支持密切相关。

Java 25 之前

import java.util.Scanner;

publicclassDoubleNumber{
publicstaticvoidmain(String[] args){
// Create a Scanner for input
        Scanner scanner = new Scanner(System.in);

// Ask for a number
        System.out.println("Enter a number:");
        String input = scanner.nextLine();

// Convert input to integer
int x = Integer.parseInt(input);

// Print double of the number
        System.out.println("Double is: " + (x * 2));

// Close the scanner
        scanner.close();
    }
}
void main() {
    IO.println("Enter a number:");
String input = IO.readln();
    int x = Integer.parseInt(input);
    IO.println("Double is: " + (x * 2));
}

灵活的构造函数体

  • 以前,Java 规定构造函数必须以调用 this(...) 或 super(...) 开头(除非是隐式调用 super())。

  • 您不能在此之前放置其他语句。

  • Java 25 放宽了这一限制:现在您可以在显式调用构造函数之前放置安全的初始化逻辑或验证(只要您不提前引用 this 对象)。

  • 这使得构造逻辑更加自然,例如,在委托给超类构造函数之前验证参数或计算派生值。

  • 它还允许更早地初始化 final 字段(只要它们不被暴露)。

classPerson{
final String name;
finalint age;

publicPerson(String name, int age){
if (name == null || name.isEmpty()) {
thrownew IllegalArgumentException("Name required");
        }
if (age < 0) {
thrownew IllegalArgumentException("Age cannot be negative");
        }
// Safe to set fields before calling super()
this.name = name;
this.age = age;
super();  // or this(...) call
// further logic if any
    }
}

作用域值

开发人员经常使用 ThreadLocal 来存储每个线程的上下文信息(例如用户 ID、请求 ID)。

classThreadLocalExample{
staticfinal ThreadLocal<String> USER = new ThreadLocal<>();

publicstaticvoidmain(String[] args){
        USER.set("Alice");    // set value for current thread
        process();
        USER.remove();        // must manually clean up!
    }

staticvoidprocess(){
        log();
    }

staticvoidlog(){
        System.out.println("User: " + USER.get());
    }
}
  • 您必须记住调用 remove() 方法移除值,否则可能会导致内存泄漏。

  • 不适用于虚拟线程(因为线程会被重用)。

  • 它可能被滥用,因为值可能会存活过长时间。

使用 ScopedValue 时,上下文具有以下特点:

  • 明确绑定到特定作用域。

  • 作用域结束时会自动清理。

  • 不可变 → 作用域内不会发生意外更改。

import java.lang.ScopedValue;

classScopedValueExample{
staticfinal ScopedValue<String> USER = ScopedValue.newInstance();

publicstaticvoidmain(String[] args){
        ScopedValue.where(USER, "Alice").run(() -> {
            process();
        }); // <-- value disappears here
    }

staticvoidprocess(){
        log();
    }

staticvoidlog(){
        System.out.println("User: " + USER.get());
    }
}
  • 无需手动清理。

  • 与虚拟线程完美兼容。

  • 每个作用域都有自己的值,不会发生数据泄露。

最新文章

随机文章