Java 9 新特性

模块系统 JPMS、JShell、集合工厂方法与 Stream 增强。

Intermediate
Key PointsJava 9 引入模块系统、JShell 交互环境、不可变集合工厂方法(List.of)与 Stream 的 takeWhile/dropWhile。

模块系统(JPMS)

module-info.java declares the module name, its dependencies (requires) and the packages it exposes (exports). It fixes classpath clashes and encapsulation leaks — the headline Java 9 feature.

Java
// 文件:module-info.java,放在源码根目录
module com.example.app {
    requires java.sql;
    requires java.logging;

    exports com.example.api;
    // 不 exports 的包,其他模块即使能 require 也访问不到
}
Ordinary projects run fine without module-info.java (they land in the unnamed module). You need it when publishing a library, enforcing API boundaries, or trimming the runtime with jlink.

JShell

jshell is the official REPL: try statements without a class or main. It supports variables, method definitions, /vars to list them and /exit to leave.

Text
$ jshell
|  欢迎使用 JShell -- 版本 21.0.2

jshell> 1 + 1
$1 ==> 2

jshell> "abc".toUpperCase()
$2 ==> "ABC"

jshell> /exit

集合工厂方法

List.of, Set.of and Map.of build immutable collections in one line — safer than Arrays.asList, which is fixed-size but mutable. They reject null elements.

Java
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FactoryDemo {
    public static void main(String[] args) {
        List<String> list = List.of("a", "b");
        Set<Integer> set = Set.of(1, 2);
        Map<String, Integer> map = Map.of("a", 1, "b", 2);

        System.out.println(list);
        System.out.println(set.size());
        System.out.println(map.get("a"));

        try {
            list.add("c");
        } catch (UnsupportedOperationException e) {
            System.out.println("immutable");
        }
    }
}
Output
[a, b]
2
1
immutable

Stream 增强

takeWhile takes from the head until the predicate first fails, dropWhile discards that prefix, and ofNullable tolerates null. All three make stream code fit real data better.

Java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Stream9Demo {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 10, 1);

        System.out.println(nums.stream().takeWhile(n -> n < 5).collect(Collectors.toList()));
        System.out.println(nums.stream().dropWhile(n -> n < 5).collect(Collectors.toList()));
        System.out.println(Stream.ofNullable(null).count());
        System.out.println(Stream.ofNullable("x").count());
    }
}
Output
[1, 2, 3]
[10, 1]
0
1

Friends & Partners