一、Java 17+ 新特性实操
1. 密封类(Sealed Classes)
应用场景:限制类的继承层级,提高代码安全性。
java
// 定义密封接口,仅允许指定的类实现
public sealed interface Shape permits Circle, Rectangle {
double area();
}
public final class Circle implements Shape {
private final double radius;
public Circle(double radius) { this.radius = radius; }
@Override
public double area() { return Math.PI * radius * radius; }
}
public final class Rectangle implements Shape {
private final double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() { return width * height; }
}
2. 模式匹配(Pattern Matching)
应用场景:简化类型判断和转换逻辑。
java
public static void printArea(Object obj) {
if (obj instanceof Shape s) { // 直接在if条件中进行类型匹配并赋值
System.out.println("Area: " + s.area());
} else {
System.out.println("Not a shape");
}
}
3. 文本块(Text Blocks)
应用场景:处理多行字符串(如JSON、SQL)。
java
String json = """
{
"name": "Doubao",
"age": 20,
"skills": ["Java", "Python"]
}
""";
二、集合框架与 Stream API 进阶
1. 集合工厂方法
应用场景:快速创建不可变集合。
java
// 创建不可变List、Set、Map
List<String> names = List.of("Alice", "Bob", "Charlie");
Set<Integer> numbers = Set.of(1, 2, 3);
Map<String, Integer> scores = Map.of("Alice", 90, "Bob", 85);
2. Stream API 高级操作
应用场景:复杂数据处理与聚合。
java
import java.util.*;
import java.util.stream.*;
public class StreamDemo {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Apple", 5.99, Category.FOOD),
new Product("Laptop", 999.99, Category.ELECTRONICS),
new Product("Bread", 2.99, Category.FOOD)
);
// 计算食品类商品的总价格
double totalFoodPrice = products.stream()
.filter(p -> p.getCategory() == Category.FOOD)
.mapToDouble(Product::getPrice)
.sum();
// 按类别分组并统计数量
Map<Category, Long> categoryCount = products.stream()
.collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));
System.out.println("Total food price: " + totalFoodPrice);
System.out.println("Category count: " + categoryCount);
}
}
enum Category { FOOD, ELECTRONICS }
record Product(String name, double price, Category category) {} // 使用record简化类定义
三、异常处理最佳实践
1. 自动资源管理(ARM)
应用场景:文件操作、网络连接等需要自动关闭资源的场景。
java
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
// try-with-resources自动关闭文件流
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 自定义异常
应用场景:业务逻辑中的特定异常处理。
java
public class AgeException extends RuntimeException {
public AgeException(String message) {
super(message);
}
}
public class UserService {
public void registerUser(String name, int age) {
if (age < 0 || age > 150) {
throw new AgeException("Invalid age: " + age);
}
// 注册逻辑...
}
}
四、多线程与并发编程
1. CompletableFuture 异步编程
应用场景:并行执行多个任务并处理结果。
java
import java.util.concurrent.*;
public class AsyncDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
// 异步任务1:查询用户信息
CompletableFuture<String> userFuture = CompletableFuture.supplyAsync(
() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) {}
return "User: Doubao";
}, executor
);
// 异步任务2:查询订单信息
CompletableFuture<String> orderFuture = CompletableFuture.supplyAsync(
() -> {
try { Thread.sleep(1500); } catch (InterruptedException e) {}
return "Order: #12345";
}, executor
);
// 合并两个任务的结果
CompletableFuture<String> combinedFuture = userFuture.thenCombine(orderFuture,
(user, order) -> user + ", " + order
);
System.out.println(combinedFuture.get()); // 输出:User: Doubao, Order: #12345
executor.shutdown();
}
}
2. ReentrantLock 显式锁
应用场景 :比synchronized
更灵活的锁控制。
java
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
五、模块化编程(Java 9+)
1. 模块定义
应用场景:将项目拆分为独立模块,控制访问权限。
java
// module-info.java
module com.example.app {
requires java.base;
requires java.sql;
exports com.example.service; // 导出服务包
uses com.example.plugin.Plugin; // 使用插件接口
}
2. 服务发现
应用场景:通过接口发现并加载实现类。
java
// 定义插件接口
package com.example.plugin;
public interface Plugin {
void execute();
}
// 模块实现
package com.example.plugin.impl;
import com.example.plugin.Plugin;
public class MyPlugin implements Plugin {
@Override
public void execute() {
System.out.println("Plugin executed");
}
}
// 服务加载
ServiceLoader<Plugin> loader = ServiceLoader.load(Plugin.class);
loader.forEach(Plugin::execute);
六、实用工具类与技巧
1. String API 增强
java
// 判断字符串是否为空白
" ".isBlank(); // true
// 字符串缩进
"Hello\nWorld".indent(2); // 每行缩进2个空格
// 重复字符串
"a".repeat(3); // "aaa"
2. 日期时间 API(Java 8+)
java
import java.time.*;
LocalDate today = LocalDate.now(); // 当前日期
LocalTime now = LocalTime.now(); // 当前时间
LocalDateTime dateTime = LocalDateTime.of(today, now); // 日期时间
// 计算两个日期之间的天数
LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
long days = ChronoUnit.DAYS.between(start, end); // 364
七、实战项目示例:图书管理系统
以下是一个简化的图书管理系统,展示Java面向对象编程的综合应用:
java
import java.util.*;
// 图书类
class Book {
private final String id;
private String title;
private String author;
private boolean isBorrowed;
public Book(String id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
this.isBorrowed = false;
}
// Getters and setters
public String getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public boolean isBorrowed() { return isBorrowed; }
public void setBorrowed(boolean borrowed) { isBorrowed = borrowed; }
@Override
public String toString() {
return "Book{id='" + id + "', title='" + title + "', author='" + author +
"', borrowed=" + isBorrowed + "}";
}
}
// 图书馆类
class Library {
private final Map<String, Book> books = new HashMap<>();
public void addBook(Book book) {
books.put(book.getId(), book);
}
public void borrowBook(String bookId) {
Book book = books.get(bookId);
if (book == null) {
System.out.println("Book not found");
return;
}
if (book.isBorrowed()) {
System.out.println("Book already borrowed");
return;
}
book.setBorrowed(true);
System.out.println("Successfully borrowed: " + book.getTitle());
}
public void returnBook(String bookId) {
Book book = books.get(bookId);
if (book == null) {
System.out.println("Book not found");
return;
}
if (!book.isBorrowed()) {
System.out.println("Book is not borrowed");
return;
}
book.setBorrowed(false);
System.out.println("Successfully returned: " + book.getTitle());
}
public void displayBooks() {
System.out.println("=== All Books ===");
books.values().forEach(System.out::println);
}
}
// 主程序
public class LibrarySystem {
public static void main(String[] args) {
Library library = new Library();
Scanner scanner = new Scanner(System.in);
// 添加示例图书
library.addBook(new Book("1", "Java Core", "Cay S. Horstmann"));
library.addBook(new Book("2", "Effective Java", "Joshua Bloch"));
while (true) {
System.out.println("\n=== Library System ===");
System.out.println("1. Display Books");
System.out.println("2. Borrow Book");
System.out.println("3. Return Book");
System.out.println("4. Exit");
System.out.print("Enter choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1 -> library.displayBooks();
case 2 -> {
System.out.print("Enter book ID to borrow: ");
library.borrowBook(scanner.nextLine());
}
case 3 -> {
System.out.print("Enter book ID to return: ");
library.returnBook(scanner.nextLine());
}
case 4 -> {
System.out.println("Exiting...");
scanner.close();
return;
}
default -> System.out.println("Invalid choice");
}
}
}
}
总结
以上实操内容涵盖了Java 17+的核心特性、集合框架高级应用、多线程编程、模块化设计等关键知识点,并通过图书管理系统示例展示了面向对象编程的综合实践。建议结合IDE(如IntelliJ IDEA)进行编码练习,加深对Java技术的理解和掌握。
Java,Java 最新技术,Java 实操,Java 基础,Java 进阶,Java 全方位指南,Java 编程语言,面向对象编程,Java 集合框架,Java 多线程,Java 性能优化,Java 微服务,Java 云原生,Java 函数式编程,Java 响应式编程
代码获取方式 pan.quark.cn/s/14fcf913b...