java不同版本特性示例

This commit is contained in:
maxf
2025-08-05 18:53:13 +08:00
parent 5c87319677
commit a4be814442
66 changed files with 1619 additions and 101 deletions

View File

@@ -0,0 +1,191 @@
## 1. HTTP/2 Client (孵化阶段)
Java 9引入了新的HTTP客户端API支持HTTP/2和WebSocket位于`jdk.incubator.http`包中。
```java
// 示例代码
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
```
## 2. Multi-Resolution Images API
支持多分辨率图像处理可以处理不同DPI的图像。
```java
// 示例代码
import java.awt.Image;
import java.awt.image.MultiResolutionImage;
// 创建多分辨率图像
MultiResolutionImage mrImage = ...;
List<Image> resolutionVariants = mrImage.getResolutionVariants();
```
## 3. @Deprecated注解增强
@Deprecated注解增加了`since``forRemoval`属性,提供更详细的弃用信息。
```java
// 示例代码在java9以后删除该方法
// since: Java 9 版本
// forRemoval: 是否计划删除该方法
@Deprecated(since = "9", forRemoval = true)
public void oldMethod() {
// 已弃用的方法
}
```
## 4. Stack Walking API
StackWalker 是 Java 9 引入的一个新 API用于高效地遍历和分析当前线程的调用栈。它提供了一种比传统的 Thread.getStackTrace() 和 Throwable.getStackTrace()
更高效、更灵活的方式来访问调用栈信息。
#### StackWalker 的用途
* 性能优化相比旧的栈跟踪方法StackWalker 提供了更好的性能
* 精确控制:可以选择性地过滤和处理栈帧信息
* 安全访问:提供了更安全的栈信息访问方式
* 灵活配置:可以根据需要配置获取不同详细程度的栈信息
#### 主要使用场景
1. 日志记录和调试
```java
// 示例代码
import java.lang.StackWalker;
import java.lang.StackWalker.StackFrame;
public static void main(String[] args) {
StackWalker.getInstance().forEach(frame ->
System.out.println("调用位置: " + frame.getClassName() +
"." + frame.getMethodName() +
"(" + frame.getLineNumber() + ")")
);
}
```
2. 安全检查和权限验证
```java
public class SecurityChecker {
public static boolean isCalledBy(String className) {
return StackWalker.getInstance().walk(stream -> stream.anyMatch(frame -> frame.getClassName().equals(className)));
}
}
```
3. 框架和库开发
```java
// ORM框架可能需要知道哪个类调用了某个方法
public class ORMFramework {
public static void logCaller() {
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.walk(stream -> {
return stream.skip(1) // 跳过当前方法
.findFirst()
.ifPresent(frame ->
System.out.println("被调用者: " + frame.getDeclaringClass())
);
});
}
}
```
4. 异常处理和上下文分析
```java
public class EnhancedException extends Exception {
public EnhancedException(String message) {
super(message);
this.addContextInfo();
}
private void addContextInfo() {
StackWalker.getInstance().walk(stream -> {
stream.limit(5) // 只获取前5个栈帧
.forEach(frame ->
System.out.println("上下文: " + frame.toString())
);
return null;
});
}
}
```
#### StackWalker 的优势
##### 相比传统方法的优势:
* 性能更好:延迟加载和流式处理,只在需要时获取栈信息
* 内存效率高:不需要创建完整的栈跟踪数组
* 功能更强大:支持过滤、映射等操作
* 类型安全:提供了 StackFrame 接口来表示栈帧信息
##### 主要API
* StackWalker.getInstance() - 获取默认的StackWalker实例
* StackWalker.getInstance(Option...) - 获取带选项的实例
* walker.forEach() - 遍历所有栈帧
* walker.walk(Function) - 使用函数式方法处理栈帧流
## 5. Reactive Streams API (Flow API)
Java 9引入了Flow API支持响应式编程。
```java
// 示例代码
import java.util.concurrent.Flow;
public class MySubscriber implements Flow.Subscriber<String> {
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(String item) {
System.out.println("Received: " + item);
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
System.err.println("Error: " + throwable);
}
@Override
public void onComplete() {
System.out.println("Completed");
}
}
```
## 6. 改进的Javadoc支持HTML5
Java 9的Javadoc工具支持生成HTML5格式的文档并提供搜索功能。
```bash
# 使用示例
javadoc -html5 -d docs src/**/*.java
```
## 7. 统一的JVM日志系统
引入了统一的JVM日志系统使用-Xlog参数进行配置。
```bash
# 示例命令
java -Xlog:gc MyApp
java -Xlog:gc*=debug:gc.log:time,tags MyApp
```
## 8. javac工具的改进
Java 9对编译器进行了多项改进包括更好的诊断信息和性能优化。
```bash
# 示例:使用新的编译器选项
javac --release 9 MyClass.java
```

View File

@@ -0,0 +1,145 @@
## Java 9 主要新特性
---
### 1. 模块系统 (Module System / Jigsaw项目)
1. Java 9引入了模块系统这是Java 9最重要的特性之一。通过[module-info.java](file://F:\coding\java-learning\demo2\java9-example\src\main\java\module-info.java)文件定义模块,可以更好地控制代码的封装和依赖关系。
<br>__示例代码__
```java
// module-info.java
module java9.example {
// 导出包供其他模块使用
exports top.yexuejc.demo;
// 声明需要使用的模块
requires java.base;
}
```
2. 模块声明语法
使用 `module` 关键字声明模块名
使用 `exports` 导出包,使其他模块可以访问
使用 `requires` 声明对其他模块的依赖
3. 模块类型
系统模块Java平台自带的模块如 `java.base`、`java.desktop` 等
应用程序模块:用户自定义的模块
自动模块传统JAR文件在模块路径上的自动模块化表示
未命名模块传统的classpath行为
4. 完整的模块指令
* `exports package`:导出包(公开)
* `exports package to module`:限定导出给特定模块
* `requires module`:依赖模块
* `requires transitive module`:传递依赖
* `uses service`:声明使用的服务
* `provides service with impl`:提供服务实现
* `opens package`:开放包反射访问
* `opens package to module`:限定开放包给特定模块
5. 编译和运行
使用模块系统编译和运行Java程序
```bash
编译
javac --module-path lib -d mods src/main/java/module-info.java src/main/java/top/yexuejc/demo/*.java
# 运行
java --module-path mods -m demo.java.example/top.yexuejc.demo.Main
```
### 2. 接口中的私有方法
Java 9允许在接口中定义私有方法提高代码复用性。
示例代码:
```java
public interface MyInterface {
private void privateMethod() {
System.out.println("Java 9 允许在接口中定义私有方法");
}
default void publicMethod() {
privateMethod(); // 调用私有方法
System.out.println("Java 9 接口私有方法示例");
}
}
```
### 3. 集合工厂方法
Java 9为List、Set和Map接口添加了静态工厂方法`of()`来创建不可变集合。
示例代码:
```java
public static void main(String[] args) {
java.util.List<String> list = java.util.List.of("a", "b", "c");
java.util.Map<String, Integer> map = java.util.Map.of("one", 1, "two", 2);
System.out.println("List: " + list);
System.out.println("Map: " + map);
}
```
### 4. Process API增强
新增了ProcessHandle接口可以更好地管理和控制操作系统进程。
示例代码:
```java
public static void main(String[] args) {
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("Current Process ID: " + currentProcess.pid());
}
```
### 5. try-with-resources改进
Java 9允许在try-with-resources语句中使用 effectively final 变量。
示例代码:
```java
public static void main(String[] args) {
MyResource resource = new MyResource();
try (resource) {
resource.use();
}
}
```
### 6. JShell (交互式Java REPL)
Java 9引入了交互式Java解释器可以在命令行中直接执行Java代码。
使用方法:
```
bash
jshell
```
## 项目结构
```
src/
├── main/
│ ├── java/
│ │ ├── top/
│ │ │ └── yexuejc/
│ │ │ └── demo/
│ │ │ ├── Main.java
│ │ │ ├── MyInterface.java
│ │ │ └── MyResource.java
│ │ └── module-info.java
```
## 运行项目
确保已安装Java 9或更高版本
```
bash
mvn compile
mvn exec:java -Dexec.mainClass="top.yexuejc.demo.Main"
```
## [其他Java 9特性](README-other.md)
- HTTP/2 Client (孵化阶段)
- Multi-Resolution Images API
- @Deprecated注解增强
- Stack Walking API
- Reactive Streams API (Flow API)
- 改进的Javadoc支持HTML5
- 统一的JVM日志系统
- javac工具的改进
## 参考资料
- [Oracle Java 9 Documentation](https://docs.oracle.com/javase/9/)
- [Java Platform, Standard Edition Documentation](https://docs.oracle.com/javase/9/docs/api/overview-summary.html)
```

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.yexuejc</groupId>
<artifactId>java9-example</artifactId>
<version>1.0.0</version>
<properties>
<java.version>9</java.version>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,8 @@
// Java 9 模块系统示例
module demo.java.example {
// 导出包供其他模块使用
exports top.yexuejc.demo;
// 需要使用的模块
requires java.base;
}

View File

@@ -0,0 +1,38 @@
package top.yexuejc.demo;
/**
* @author maxiaofeng
* @date 2025/7/18 10:06
*/
public class Main {
public static void main(String[] args) {
System.out.println("hello java9.");
// Java 9 新特性示例
// 1. 模块系统 (Module System)
// 请参考 module-info.java 文件
// 2. JShell (交互式Java REPL)
// 可在命令行中使用 jshell 命令体验
// 3. 接口中的私有方法
MyInterface myInterface = new MyInterface() {};
myInterface.publicMethod();
// 4. 集合工厂方法
java.util.List<String> list = java.util.List.of("a", "b", "c");
java.util.Map<String, Integer> map = java.util.Map.of("one", 1, "two", 2);
System.out.println("List: " + list);
System.out.println("Map: " + map);
// 5. Process API增强 新增了ProcessHandle接口可以更好地管理和控制操作系统进程。
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("Current Process ID: " + currentProcess.pid());
// 6. try-with-resources改进
MyResource resource = new MyResource();
try (resource) {
resource.use();
}
}
}

View File

@@ -0,0 +1,16 @@
package top.yexuejc.demo;
/**
* 接口中的私有方法示例
* @author maxiaofeng
* @date 2025/8/5 17:11
*/
public interface MyInterface {
private void privateMethod() {
System.out.println("Java 9 允许在接口中定义私有方法");
}
default void publicMethod() {
privateMethod(); // 调用私有方法
System.out.println("Java 9 接口私有方法示例");
}
}

View File

@@ -0,0 +1,17 @@
package top.yexuejc.demo;
/**
* try-with-resources改进示例
* @author maxiaofeng
* @date 2025/8/5 17:21
*/
public class MyResource implements AutoCloseable {
public void use() {
System.out.println("使用资源");
throw new RuntimeException("使用资源时出错");
}
@Override
public void close() {
System.out.println("资源已关闭");
}
}

View File

@@ -0,0 +1,32 @@
package top.yexuejc.demo;
import java.lang.StackWalker;
public class StackWalkerDemo {
public static void main(String[] args) {
methodA();
}
public static void methodA() {
methodB();
}
public static void methodB() {
// 使用StackWalker打印调用栈
System.out.println("=== 完整调用栈 ===");
StackWalker.getInstance().forEach(System.out::println);
System.out.println("\n=== 过滤后的调用栈 ===");
// 只显示自定义类的调用栈
StackWalker.getInstance()
.walk(stackFrameStream ->
stackFrameStream
.filter(frame -> frame.getClassName().contains("StackWalkerDemo"))
.peek(frame -> System.out.println(frame.getClassName() + "." + frame.getMethodName()))
);
System.out.println("\n=== 调用者信息 ===");
// 获取直接调用者信息
StackWalker.getInstance().walk(stackStream -> stackStream.skip(1).findFirst()).ifPresent(caller -> System.out.println("调用者: " + caller.getClassName() + "." + caller.getMethodName()));
}
}