一、java.lang
自动导入,无需 import
| 类 | 作用 |
|---|---|
Object | 所有类的父类 |
String | 字符串,不可变 |
StringBuilder / StringBuffer | 可变字符串,前者非线程安全,后者线程安全 |
Math | 数学运算(abs、sqrt、random 等) |
System | 标准输入/输出、数组拷贝、环境属性 |
Thread | 线程操作 |
Class | 反射时获取类的元信息 |
Enum | 所有枚举的父类 |
Runtime | 获取 JVM 运行时信息 |
Integer, Long, Double 等 | 基本类型的包装类,提供类型转换、缓存池 |
代码案例
public class LangUtilsDemo {
public static void main(String[] args) throws Exception {
// ========== Object(所有类的父类) ==========
class Person {
String name;
Person(String name) { this.name = name; }
@Override
public String toString() { return "Person:" + name; }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Person)) return false;
return name.equals(((Person) obj).name);
}
@Override
public int hashCode() { return name.hashCode(); }
}
Person p = new Person("张三");
System.out.println(p.toString()); // Person:张三
System.out.println(p.getClass().getName()); // 包名.Person
System.out.println(p.hashCode()); // 哈希码
Person p2 = new Person("张三");
System.out.println(p.equals(p2)); // true(需重写equals)
// ========== String(不可变字符串) ==========
String s = "Hello";
String s2 = s.concat(" World"); // 生成新字符串,原串不变
System.out.println(s2); // Hello World
System.out.println(s.length()); // 5
System.out.println(s.charAt(1)); // e
System.out.println(s.substring(1,4)); // ell
System.out.println(s.indexOf('l')); // 2
System.out.println(s.replace('l', 'x')); // Hexxo
// 字符串比较(必须用equals,不能用==)
System.out.println("abc".equals("Abc")); // false
System.out.println("abc".equalsIgnoreCase("Abc")); // true
// ========== StringBuilder / StringBuffer(可变字符串) ==========
StringBuilder sb = new StringBuilder(); // 非线程安全,性能高(推荐单线程)
sb.append("Hello").append(" ").append("World");
sb.insert(5, ","); // Hello, World
sb.replace(6, 11, "Java"); // Hello,Java
sb.deleteCharAt(5); // HelloJava
sb.reverse(); // avaJolleH
String result = sb.toString();
StringBuffer sbf = new StringBuffer(); // 线程安全(方法同步),性能略低
sbf.append("线程安全");
// ========== Math(数学运算) ==========
System.out.println(Math.abs(-10)); // 10(绝对值)
System.out.println(Math.max(5, 3)); // 5
System.out.println(Math.min(5, 3)); // 3
System.out.println(Math.pow(2, 10)); // 1024.0
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.random()); // [0.0,1.0) 随机数
System.out.println(Math.round(3.6)); // 4(四舍五入)
System.out.println(Math.ceil(3.1)); // 4.0(向上取整)
System.out.println(Math.floor(3.9)); // 3.0(向下取整)
// ========== System(标准输入输出、环境、数组拷贝) ==========
System.out.println("输出到控制台"); // 标准输出
System.err.println("错误输出"); // 标准错误
long start = System.currentTimeMillis(); // 毫秒时间戳
long nano = System.nanoTime(); // 纳秒(用于性能测量)
int[] src = {1,2,3,4};
int[] dest = new int[4];
System.arraycopy(src, 0, dest, 0, 4); // 数组拷贝
System.getProperties().list(System.out); // 打印所有系统属性
String javaVersion = System.getProperty("java.version");
System.gc(); // 建议JVM执行GC(不保证)
// ========== Thread(线程操作,已在多线程笔记中,这里简要演示) ==========
Thread t = new Thread(() -> System.out.println("线程运行"));
t.start();
Thread.sleep(100); // 当前线程休眠100毫秒
Thread.currentThread().getName(); // 获取当前线程名
// ========== Class(反射入口,获取类元信息) ==========
Class<?> clazz = String.class;
System.out.println(clazz.getName()); // java.lang.String
System.out.println(clazz.getSimpleName()); // String
System.out.println(clazz.getSuperclass()); // class java.lang.Object
// ========== Enum(枚举父类) ==========
enum Color { RED, GREEN, BLUE }
Color c = Color.RED;
System.out.println(c.name()); // RED
System.out.println(c.ordinal()); // 0(声明顺序)
System.out.println(c.toString()); // RED
Color parsed = Enum.valueOf(Color.class, "GREEN"); // GREEN
// ========== Runtime(JVM运行时信息) ==========
Runtime rt = Runtime.getRuntime();
System.out.println("处理器核心数: " + rt.availableProcessors());
System.out.println("总内存: " + rt.totalMemory() / 1024 / 1024 + " MB");
System.out.println("空闲内存: " + rt.freeMemory() / 1024 / 1024 + " MB");
// rt.exec("notepad.exe"); // 执行外部程序(需处理异常)
// ========== 包装类(Integer, Long, Double等) ==========
// 自动装箱/拆箱
Integer i = 100; // 自动装箱:Integer.valueOf(100)
int j = i; // 自动拆箱:i.intValue()
// 字符串转基本类型
int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
// 进制转换
String bin = Integer.toBinaryString(10); // "1010"
String hex = Integer.toHexString(255); // "ff"
// 缓存池(-128 到 127 的 Integer 使用缓存)
Integer a1 = 127;
Integer a2 = 127;
System.out.println(a1 == a2); // true(缓存)
Integer b1 = 128;
Integer b2 = 128;
System.out.println(b1 == b2); // false(new不同对象)
// 推荐使用 equals 比较包装类,避免缓存陷阱
// 其他常用方法
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Double.NaN); // NaN
}
}
二、java.util
集合类(最常用)具体参考java集合框架文档
| 类 | 底层 | 特点 |
|---|---|---|
ArrayList | 动态数组 | 随机访问快,增删慢(末尾快) |
LinkedList | 双向链表 | 增删快(两端/已知节点),随机访问慢 |
HashSet | 哈希表 | 无序、元素不可重复 |
TreeSet | 红黑树 | 有序(自然排序或 Comparator) |
HashMap | 哈希表+链表+红黑树 | 键值对,无序,允许 null 键 |
TreeMap | 红黑树 | 键有序(自然排序或 Comparator) |
LinkedHashMap | 哈希表+双向链表 | 保持插入顺序或访问顺序 |
PriorityQueue | 堆 | 优先级队列,默认小顶堆 |
工具类
| 类 | 用途 |
|---|---|
Collections | 操作集合的静态方法:排序、反转、打乱、同步包装等 |
Arrays | 操作数组的静态方法:排序、二分查找、数组转 List |
Objects | 对对象操作(Java 7+):equals()、hashCode()、requireNonNull() |
Optional | 优雅处理可能为 null 的值(Java 8+) |
Scanner | 解析简单输入(键盘、文件) |
Random | 生成伪随机数 |
UUID | 生成唯一标识符 |
Date / Calendar | 旧版日期时间(不推荐,应使用 java.time) |
代码案例
import java.util.*;
import java.util.function.*;
public class UtilsDemo {
public static void main(String[] args) {
// ========== Collections ==========
List<Integer> list = new ArrayList<>(Arrays.asList(3,1,4,1,5));
Collections.sort(list); // 升序排序 → [1,1,3,4,5]
Collections.reverse(list); // 反转顺序 → [5,4,3,1,1]
Collections.shuffle(list); // 随机打乱顺序
// 返回线程安全的List包装(每个方法都同步)
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
// ========== Arrays ==========
int[] arr = {3,1,4,1,5};
Arrays.sort(arr); // 对数组升序排序 → [1,1,3,4,5]
// 二分查找(必须先排序),返回索引,找不到返回负数
int idx = Arrays.binarySearch(arr, 4); // 3
// 将数组转为固定长度的List(不可增删,但可改元素)
List<String> strList = Arrays.asList("A","B","C");
// ========== Objects (Java 7+) ==========
String s1 = null, s2 = "hello";
// 安全的equals:不会因s1为null而抛NPE
Objects.equals(s1, s2); // false
// 根据多个字段生成hashCode
int hash = Objects.hash(1, "abc");
// 检查参数非空,为空则抛出NullPointerException,可自定义错误消息
Objects.requireNonNull(s2, "参数不能为空"); // 返回s2本身
// ========== Optional (Java 8+) ==========
Optional<String> opt = Optional.of("value"); // 创建必含值的Optional(不能为null)
// 如果值存在则执行Consumer
opt.ifPresent(System.out::println); // 打印 "value"
// 值存在则返回该值,否则返回默认值
String res = opt.orElse("default"); // "value"
// 允许值为null的Optional创建,若值为null则等同于empty
String other = Optional.ofNullable(null).orElse("default"); // "default"
// ========== Scanner ==========
Scanner sc = new Scanner(System.in);
System.out.print("输入整数: ");
int n = sc.nextInt(); // 读取整数(不处理换行符)
sc.nextLine(); // 消耗整数后的换行符
System.out.print("输入一行文字: ");
String line = sc.nextLine(); // 读取整行
sc.close(); // 关闭扫描器(释放资源)
// ========== Random ==========
Random rand = new Random();
int r1 = rand.nextInt(100); // 生成 [0,100) 的随机整数
double r2 = rand.nextDouble(); // 生成 [0.0,1.0) 的随机小数
long r3 = rand.nextLong(); // 随机长整数
// ========== UUID ==========
UUID uuid = UUID.randomUUID(); // 生成随机UUID(版本4)
String uuidStr = uuid.toString(); // 转为标准36位字符串
// ========== Date / Calendar(旧版,不推荐)==========
Date now = new Date(); // 当前时间(包含日期和时间)
Calendar cal = Calendar.getInstance(); // 获取当前日历实例
cal.set(2024, Calendar.DECEMBER, 31); // 设置为2024年12月31日(月份从0开始,注意)
Date specific = cal.getTime(); // 转换为Date对象
// 推荐使用 java.time (Java 8+)
// LocalDate.now(), LocalDateTime.now(), DateTimeFormatter.ofPattern("yyyy-MM-dd")
}
}
三、java.time
Java 8+ 推荐日期时间 API
| 类 | 用途 | 示例 |
|---|---|---|
LocalDate | 日期(年-月-日) | LocalDate.now()、LocalDate.of(2025, 5, 17) |
LocalTime | 时间(时:分:秒.纳秒) | LocalTime.of(14, 30) |
LocalDateTime | 日期 + 时间 | 最常用的组合 |
ZonedDateTime | 带时区的日期时间 | 跨时区使用 |
Instant | 时间戳(机器时间) | Instant.now().toEpochMilli() |
Duration | 时间间隔(秒/纳秒) | Duration.between(start, end) |
Period | 日期间隔(年/月/日) | Period.between(date1, date2) |
DateTimeFormatter | 日期格式化/解析(线程安全) | formatter.format(localDate) |
代码案例
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class JavaTimeDemo {
public static void main(String[] args) {
// ========== LocalDate(日期) ==========
LocalDate today = LocalDate.now(); // 当前日期(系统默认时区)
LocalDate birthday = LocalDate.of(2025, 5, 17); // 指定年-月-日
int year = birthday.getYear(); // 2025
Month month = birthday.getMonth(); // MAY
int dayOfMonth = birthday.getDayOfMonth(); // 17
// ========== LocalTime(时间) ==========
LocalTime nowTime = LocalTime.now(); // 当前时间(含纳秒)
LocalTime meetingTime = LocalTime.of(14, 30); // 14:30
LocalTime withSeconds = LocalTime.of(14, 30, 15); // 14:30:15
int hour = meetingTime.getHour(); // 14
// ========== LocalDateTime(日期+时间) ==========
LocalDateTime nowDateTime = LocalDateTime.now(); // 最常用
LocalDateTime specific = LocalDateTime.of(2025, 5, 17, 14, 30, 0);
// 可以从LocalDate和LocalTime组合
LocalDateTime fromParts = LocalDate.now().atTime(14, 30);
// ========== ZonedDateTime(带时区) ==========
ZonedDateTime nowBeijing = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
// 转换时区
ZonedDateTime beijingToNewYork = nowBeijing.withZoneSameInstant(ZoneId.of("America/New_York"));
// ========== Instant(时间戳,机器时间) ==========
Instant nowInstant = Instant.now(); // UTC时间戳
long epochMillis = nowInstant.toEpochMilli(); // 毫秒数(同 System.currentTimeMillis())
Instant fromMillis = Instant.ofEpochMilli(1710000000000L);
// ========== Duration(时间间隔,秒/纳秒) ==========
LocalTime start = LocalTime.of(10, 0);
LocalTime end = LocalTime.of(12, 30);
Duration duration = Duration.between(start, end); // PT2H30M(2小时30分)
long minutes = duration.toMinutes(); // 150
long seconds = duration.getSeconds(); // 9000
// ========== Period(日期间隔,年/月/日) ==========
LocalDate date1 = LocalDate.of(2025, 1, 1);
LocalDate date2 = LocalDate.of(2025, 12, 31);
Period period = Period.between(date1, date2); // P11M30D(11个月30天)
int months = period.getMonths(); // 11
int days = period.getDays(); // 30
// ========== DateTimeFormatter(格式化/解析,线程安全) ==========
// 预定义格式
DateTimeFormatter isoDate = DateTimeFormatter.ISO_LOCAL_DATE; // 2025-05-17
String formattedDate = isoDate.format(LocalDate.now());
// 自定义格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime dt = LocalDateTime.of(2025, 5, 17, 14, 30, 0);
String formatted = formatter.format(dt); // "2025年05月17日 14:30:00"
// 解析字符串
LocalDate parsed = LocalDate.parse("2025-05-17"); // 默认格式 yyyy-MM-dd
LocalDateTime parsedCustom = LocalDateTime.parse("2025年05月17日 14:30:00", formatter);
// 注意:Duration 和 Period 的区别:Duration 用于时间(时/分/秒),Period 用于日期(年/月/日)
// 所有 java.time 类都不可变且线程安全,推荐完全替代 Date/Calendar
}
}
四、java.io 与 java.nio
输入和输出
| 类 | 用途 |
|---|---|
File | 文件和目录路径抽象(仅路径操作,不读写内容) |
Files | 现代文件操作(Java 7+):readAllLines()、copy()、walk() |
Path / Paths | 更安全灵活的文件路径表示 |
BufferedReader / BufferedWriter | 字符缓冲流,带缓存,高效读写文本文件 |
InputStream / OutputStream | 字节流父类 |
FileInputStream / FileOutputStream | 文件字节流,用于二进制文件 |
ObjectInputStream / ObjectOutputStream | 对象序列化/反序列化 |
现代推荐:优先使用
java.nio.file.Files和Path,比File功能更强、更安全。代码案例
import java.io.*;
import java.nio.file.*;
import java.util.List;
public class IODemo {
public static void main(String[] args) throws IOException {
// ========== File(仅路径操作,不读写内容)==========
File file = new File("demo.txt"); // 相对路径(项目根目录)
file.exists(); // 判断文件/目录是否存在
file.isFile(); // 是否为文件
file.isDirectory(); // 是否为目录
file.createNewFile(); // 创建空文件(返回boolean)
file.mkdir(); // 创建单级目录
file.mkdirs(); // 创建多级目录
file.delete(); // 删除文件/目录
String path = file.getAbsolutePath(); // 获取绝对路径
// ========== Path / Paths(更安全灵活)==========
Path p = Paths.get("data", "user.txt"); // 自动处理路径分隔符
Path absolutePath = p.toAbsolutePath(); // 转绝对路径
Path parent = p.getParent(); // 父路径
// ========== Files(现代文件操作,Java 7+)==========
// 一次性读取所有行(适用于小文件)
List<String> lines = Files.readAllLines(Paths.get("input.txt"));
// 写入文本(自动创建文件,覆盖原有内容)
Files.write(Paths.get("output.txt"), "Hello World".getBytes());
// 复制文件
Files.copy(Paths.get("src.txt"), Paths.get("dest.txt"), StandardCopyOption.REPLACE_EXISTING);
// 遍历目录(递归)
try (var stream = Files.walk(Paths.get("."))) {
stream.forEach(System.out::println);
}
// ========== BufferedReader / BufferedWriter(字符流,高效读写文本)==========
// 读文本文件
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
// 写文本文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("第一行");
bw.newLine(); // 写入换行符
bw.write("第二行");
}
// ========== InputStream / OutputStream(字节流,二进制数据)==========
// 读取字节文件
try (InputStream is = new FileInputStream("image.jpg")) {
int data;
while ((data = is.read()) != -1) { // 逐个字节读取(低效)
// 处理 data
}
}
// 更高效的批量读取
try (InputStream is = new FileInputStream("large.bin")) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
// 处理 buffer 中前 bytesRead 个字节
}
}
// ========== FileInputStream / FileOutputStream(文件字节流)==========
// 复制二进制文件(一次读写一个字节数组)
try (FileInputStream fis = new FileInputStream("src.zip");
FileOutputStream fos = new FileOutputStream("dst.zip")) {
byte[] buf = new byte[8192];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
}
// ========== ObjectInputStream / ObjectOutputStream(对象序列化)==========
// 要求被序列化的类实现 Serializable 接口
class User implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
User(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return name + ":" + age; }
}
// 序列化对象到文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
oos.writeObject(new User("张三", 25));
}
// 反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
User user = (User) ois.readObject();
System.out.println(user);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 注意:以上所有资源都使用 try-with-resources 自动关闭,无需手动 close
}
}
五、java.util.concurrent
并发编程常用
| 类/接口 | 用途 |
|---|---|
Thread | 线程类,可继承重写 run() |
Runnable | 任务接口,无返回值 |
Callable<V> | 任务接口,有返回值 |
ExecutorService | 线程池管理,常用实现:Executors.newFixedThreadPool() |
ConcurrentHashMap | 高并发安全的 HashMap(分段锁/CAS) |
AtomicInteger / AtomicLong | 原子变量,无锁线程安全 |
Lock / ReentrantLock | 显式锁,比 synchronized 更灵活 |
CountDownLatch | 等待一组线程完成 |
BlockingQueue 接口 | 阻塞队列,实现类:ArrayBlockingQueue、LinkedBlockingQueue |
代码案例
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
public class ConcurrencyDemo {
public static void main(String[] args) throws Exception {
// ========== Thread(继承Thread类) ==========
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
Thread t1 = new MyThread();
t1.start(); // 启动线程
// ========== Runnable(无返回值) ==========
Runnable task = () -> System.out.println("Runnable任务执行");
Thread t2 = new Thread(task);
t2.start();
// ========== Callable<V>(有返回值 + 可抛异常) ==========
Callable<Integer> callable = () -> {
TimeUnit.SECONDS.sleep(1);
return 42;
};
// Callable通常配合Future使用(ExecutorService提交)
// ========== ExecutorService(线程池) ==========
ExecutorService pool = Executors.newFixedThreadPool(3); // 固定大小线程池
// 提交Runnable
pool.execute(() -> System.out.println("任务1"));
// 提交Callable,获取Future
Future<Integer> future = pool.submit(callable);
Integer result = future.get(); // 阻塞直到完成,获取42
System.out.println("Callable返回:" + result);
pool.shutdown(); // 优雅关闭(不再接收新任务)
// ========== ConcurrentHashMap(高并发安全Map) ==========
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
map.putIfAbsent("B", 2); // 原子操作:不存在则放入
map.computeIfAbsent("C", k -> k.length()); // 不存在则计算并放入
map.forEach((k, v) -> System.out.println(k + "=" + v));
// ========== AtomicInteger / AtomicLong(无锁原子变量) ==========
AtomicInteger counter = new AtomicInteger(0);
// 线程安全自增
int newVal = counter.incrementAndGet(); // ++i
int oldVal = counter.getAndIncrement(); // i++
boolean updated = counter.compareAndSet(1, 100); // CAS操作
// ========== Lock / ReentrantLock(显式锁,更灵活) ==========
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
System.out.println("加锁保护");
} finally {
lock.unlock(); // 必须在finally中释放
}
// 尝试加锁(非阻塞)
if (lock.tryLock()) {
try {
// 获得锁后的操作
} finally {
lock.unlock();
}
}
// ========== CountDownLatch(等待一组线程完成) ==========
int threadCount = 3;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 完成");
latch.countDown(); // 计数减1
}).start();
}
latch.await(); // 主线程等待,直到计数为0
System.out.println("所有线程都已完成");
// ========== BlockingQueue(阻塞队列,生产者-消费者模式) ==========
BlockingQueue<String> queue = new ArrayBlockingQueue<>(5); // 有界队列
// 生产者
Thread producer = new Thread(() -> {
try {
queue.put("消息"); // 队列满时阻塞
// 也可用 offer(e, timeout, unit) 超时不阻塞
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 消费者
Thread consumer = new Thread(() -> {
try {
String msg = queue.take(); // 队列空时阻塞
System.out.println("消费:" + msg);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
// 其他常用阻塞队列实现:LinkedBlockingQueue(无界或可选有界)、SynchronousQueue(直接传递)
}
}
六、其他重要类
| 包 | 类 | 用途 |
|---|---|---|
java.net | URL / HttpURLConnection | 旧版 HTTP 请求 |
java.net.http(Java 11+) | HttpClient | 现代 HTTP 客户端 |
java.util.regex | Pattern / Matcher | 正则表达式 |
java.math | BigDecimal / BigInteger | 高精度数值计算(金融、大数) |
java.lang.reflect | Method / Field / Constructor | 反射操作类/对象 |
代码案例
import java.net.*;
import java.net.http.*;
import java.time.Duration;
import java.util.regex.*;
import java.math.*;
import java.lang.reflect.*;
public class OtherUtilsDemo {
public static void main(String[] args) throws Exception {
// ========== java.net:URL / HttpURLConnection(旧版) ==========
URL url = new URL("https://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 设置请求方式
conn.setConnectTimeout(5000); // 连接超时(毫秒)
int responseCode = conn.getResponseCode(); // 获取响应码
// 读取响应流(略)
conn.disconnect(); // 关闭连接
// ========== java.net.http:HttpClient(Java 11+,推荐) ==========
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com"))
.timeout(Duration.ofSeconds(10)) // 超时
.header("User-Agent", "Java HttpClient")
.GET() // GET请求
.build();
// 同步发送
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("状态码:" + response.statusCode());
System.out.println("响应体:" + response.body().substring(0, 100));
// 异步发送(非阻塞)
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
// ========== java.util.regex:Pattern / Matcher ==========
String text = "我的电话是13812345678,备用电话13987654321";
Pattern pattern = Pattern.compile("1[3-9]\\d{9}"); // 手机号正则
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("找到号码:" + matcher.group()); // 13812345678, 13987654321
}
// 使用预编译Pattern提升性能
boolean matches = Pattern.matches("\\d+", "12345"); // true
// ========== java.math:BigDecimal / BigInteger ==========
// BigDecimal:精确小数(金融计算必须使用)
BigDecimal price = new BigDecimal("19.99");
BigDecimal taxRate = new BigDecimal("0.07");
BigDecimal tax = price.multiply(taxRate); // 乘法
BigDecimal total = price.add(tax); // 加法
// 设置小数位数和舍入模式
BigDecimal rounded = total.setScale(2, RoundingMode.HALF_UP);
System.out.println("总计:" + rounded); // 21.39
// BigInteger:大整数
BigInteger big1 = new BigInteger("12345678901234567890");
BigInteger big2 = BigInteger.valueOf(9876543210L);
BigInteger product = big1.multiply(big2); // 乘法
BigInteger gcd = big1.gcd(big2); // 最大公约数
// ========== java.lang.reflect:反射 ==========
// 示例类
class Person {
private String name = "张三";
public int age = 25;
public void sayHello(String msg) { System.out.println("Hello " + msg); }
private void secret() { System.out.println("私有方法"); }
}
Class<?> clazz = Person.class;
// 获取所有公共字段
Field[] fields = clazz.getFields(); // 只有 public age
Field privateField = clazz.getDeclaredField("name"); // 获取私有字段
privateField.setAccessible(true); // 绕过访问检查
// 获取所有公共方法(包括继承的)
Method[] methods = clazz.getMethods();
Method sayHello = clazz.getMethod("sayHello", String.class);
// 获取构造器
Constructor<?> constructor = clazz.getConstructor();
Object obj = constructor.newInstance(); // 创建实例
// 调用方法
sayHello.invoke(obj, "World"); // 输出:Hello World
// 修改私有字段
privateField.set(obj, "李四");
System.out.println("修改后name:" + privateField.get(obj)); // 李四
// 调用私有方法(setAccessible + invoke)
Method secretMethod = clazz.getDeclaredMethod("secret");
secretMethod.setAccessible(true);
secretMethod.invoke(obj); // 输出:私有方法
}
}