Apache Commons【一、简介】
Apache Commons 是 Java 生态系统中最基础、最广泛使用的开源工具库集合。它填补了 JDK 标准库在很多通用场景下的空白,提供了高质量、经过生产验证的工具类。
截至 2026 年,虽然 Java 8-21 的新特性(如 Stream, Optional, Var, Records)吸收了一些功能,但 Commons 在兼容性、功能深度和特定领域(如数学统计、编解码、旧版系统支持)依然不可替代。
以下是核心模块的功能全景图、原理简述及详细代码示例。
📦 Apache Commons 核心模块全景图
| 模块名称 | 核心定位 | 典型应用场景 | 状态 |
|---|---|---|---|
| Commons Lang | 语言级增强 (String, Object, Array) | 字符串处理、对象克隆、数组操作 | 🔥 极高频 |
| Commons IO | IO 流操作增强 | 文件复制、流转换、监控文件变化 | 🔥 极高频 |
| Commons Collections | 集合框架增强 | 高级集合操作、双向映射、布隆过滤器 | 🔥 高频 |
| Commons BeanUtils | JavaBean 属性操作 | Web 参数绑定、对象拷贝、动态属性 | 🔥 高频 |
| Commons Codec | 编解码工具 | Base64, MD5, SHA, URL 编码 | ⚡ 常用 |
| Commons Text | 文本处理 (Lang 的扩展) | 字符串替换、转义、随机字符串生成 | ⚡ 常用 |
| Commons Math | 数学与统计 | 统计分析、线性代数、优化算法 | 🛠 专业领域 |
| Commons Configuration | 配置管理 | 读取多种格式配置文件 (XML, Properties, JSON) | 🛠 专业领域 |
| Commons CLI | 命令行解析 | 解析启动参数 (-h, --port 8080) |
🛠 专业领域 |
| Commons Pool | 对象池化 | 数据库连接池底层、线程池对象复用 | 🛠 底层支撑 |
1. Commons Lang (org.apache.commons:commons-lang3)
定位:java.lang 包的超级增强版。解决 String、Object、Array、System 等日常痛点。
核心 API 与示例
A. 字符串处理 (StringUtils)
比 JDK 更健壮,自动处理 null,避免 NullPointerException。
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
public class LangDemo {
public static void main(String[] args) {
// 1. 空值检查 (推荐替代 "".equals(s))
System.out.println(StringUtils.isEmpty(null)); // true
System.out.println(StringUtils.isBlank(" ")); // true (包含空格)
System.out.println(StringUtils.isNotBlank("Hi")); // true
// 2. 默认值设置
String name = null;
System.out.println(StringUtils.defaultString(name, "Unknown")); // "Unknown"
// 3. 字符串操作
System.out.println(StringUtils.reverse("Hello")); // "olleH"
System.out.println(StringUtils.capitalize("hello world"));// "Hello world"
System.out.println(StringUtils.join(new String[]{"A", "B"}, "-")); // "A-B"
// 4. 缩写
System.out.println(StringUtils.abbreviate("Apache Commons", 10)); // "Apache C..."
}
}
B. 对象操作 (ObjectUtils, ReflectionUtils)
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
class Person {
String name; int age;
// constructor...
@Override
public String toString() {
// 一行代码生成漂亮的 toString,支持循环引用检测
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
// 使用
Person p = new Person("Jack", 25);
System.out.println(p);
// 输出: {"name":"Jack","age":25}
// 安全比较 (处理 null)
System.out.println(ObjectUtils.equals(null, null)); // true
System.out.println(ObjectUtils.max(10, 20, 5)); // 20
C. 数组操作 (ArrayUtils)
int[] nums = {1, 2, 3};
nums = ArrayUtils.add(nums, 4); // [1, 2, 3, 4]
nums = ArrayUtils.remove(nums, 0); // [2, 3, 4]
ArrayUtils.reverse(nums); // [4, 3, 2]
System.out.println(ArrayUtils.contains(nums, 3)); // true
2. Commons IO (commons-io:commons-io)
定位:简化 java.io 和 java.nio 的繁琐操作。
核心 API 与示例
A. 文件读写 (FileUtils)
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class IODemo {
public static void main(String[] args) throws Exception {
File file = new File("data.txt");
// 1. 一键写入 (自动创建父目录)
FileUtils.write(file, "Hello Commons IO", StandardCharsets.UTF_8);
// 2. 一键读取
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
// 3. 读取为行列表
List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);
// 4. 复制文件/目录
FileUtils.copyFile(file, new File("backup.txt"));
FileUtils.copyDirectory(new File("src"), new File("dest"));
// 5. 删除目录 (递归)
// FileUtils.deleteDirectory(new File("temp"));
// 6. 获取文件大小人类可读格式
long size = file.length();
System.out.println(FileUtils.byteCountToDisplaySize(size)); // "15 bytes"
}
}
B. 流操作 (IOUtils)
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;
// 复制流 (自动关闭资源,无需 try-with-resources 显式写)
try (InputStream in = new FileInputStream("src.txt");
OutputStream out = new FileOutputStream("dst.txt")) {
IOUtils.copy(in, out);
}
// 从 URL 读取内容
String html = IOUtils.toString(new URL("https://apache.org"), StandardCharsets.UTF_8);
// 将大字符串转为输入流
InputStream stream = IOUtils.toInputStream("Large Data...", StandardCharsets.UTF_8);
C. 文件监控 (FileMonitor)
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import java.io.File;
// 监听文件夹变化
File folder = new File("/var/log/myapp");
FileAlterationObserver observer = new FileAlterationObserver(folder);
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
System.out.println("New file created: " + file.getName());
}
@Override
public void onFileChange(File file) {
System.out.println("File modified: " + file.getName());
}
});
// 需要配合 Timer 或线程定期调用 observer.checkAndNotify()
3. Commons Collections (org.apache.commons:commons-collections4)
定位:超越 java.util 的高级数据结构。
核心 API 与示例
A. 双向映射 (BidiMap)
允许通过 Key 查 Value,也允许通过 Value 查 Key。
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
BidiMap<String, Integer> map = new TreeBidiMap<>();
map.put("One", 1);
map.put("Two", 2);
System.out.println(map.get("One")); // 1
System.out.println(map.getKey(2)); // "Two" (原生 Map 做不到)
map.removeValue(1); // 根据值删除
B. 多值映射 (MultiValuedMap)
一个 Key 对应多个 Value,无需手动 List<V>。
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
MultiValuedMap<String, String> multiMap = new ArrayListValuedHashMap<>();
multiMap.put("Fruit", "Apple");
multiMap.put("Fruit", "Banana");
multiMap.put("Color", "Red");
System.out.println(multiMap.get("Fruit")); // [Apple, Banana]
System.out.println(multiMap.keySet()); // [Fruit, Color]
C. 集合工具类 (CollectionUtils)
import org.apache.commons.collections4.CollectionUtils;
import java.util.*;
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
// 交集
Collection<Integer> intersection = CollectionUtils.intersection(list1, list2); // [3, 4]
// 并集
Collection<Integer> union = CollectionUtils.union(list1, list2); // [1, 2, 3, 4, 5, 6]
// 差集 (list1 有但 list2 没有)
Collection<Integer> subtract = CollectionUtils.subtract(list1, list2); // [1, 2]
// 判空
if (CollectionUtils.isNotEmpty(list1)) { ... }
D. 布隆过滤器 (BloomFilter - 需引入 guava 或 commons-collections 扩展)
注:Commons Collections 4 主要侧重集合结构,高性能布隆过滤器通常推荐 Guava,但 Commons 提供了基础的过滤逻辑。
4. Commons Codec (commons-codec:commons-codec)
定位:通用的编解码算法实现。
核心 API 与示例
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import java.nio.charset.StandardCharsets;
public class CodecDemo {
public static void main(String[] args) throws Exception {
String data = "Secret Password 123";
// 1. 哈希摘要 (MD5, SHA-1, SHA-256)
String md5 = DigestUtils.md5Hex(data);
String sha256 = DigestUtils.sha256Hex(data);
System.out.println("MD5: " + md5);
// 2. Base64 编码/解码
byte[] encoded = Base64.encodeBase64(data.getBytes(StandardCharsets.UTF_8));
String base64Str = new String(encoded, StandardCharsets.UTF_8);
byte[] decoded = Base64.decodeBase64(base64Str);
System.out.println("Base64: " + base64Str);
// 3. URL 编码/解码 (处理特殊字符)
URLCodec codec = new URLCodec();
String urlData = "a b & c=d";
String encodedUrl = codec.encode(urlData); // "a+b+%26+c%3Dd"
System.out.println("URL Encoded: " + encodedUrl);
}
}
5. Commons Text (org.apache.commons:commons-text)
定位:从 Lang 3 中剥离出来的高级文本处理库(Lang 3.6+ 开始独立)。
核心 API 与示例
import org.apache.commons.text.StringSubstitutor;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.commons.text.translate.EscapeHtml;
import java.util.HashMap;
import java.util.Map;
public class TextDemo {
public static void main(String[] args) {
// 1. 字符串模板替换 (类似 Velocity 简单版)
Map<String, String> values = new HashMap<>();
values.put("name", "Alice");
values.put("job", "Engineer");
String template = "Hello ${name}, you are a ${job}.";
StringSubstitutor substitutor = new StringSubstitutor(values);
String result = substitutor.replace(template);
System.out.println(result); // "Hello Alice, you are a Engineer."
// 2. HTML 转义 (防 XSS)
String html = "<script>alert('xss')</script>";
String safeHtml = EscapeHtml.escapeHtml4(html);
System.out.println(safeHtml); // "<script>alert('xss')</script>"
// 3. 随机字符串生成
// 注意:RandomStringGenerator 在较新版本中被标记,推荐使用 SecureRandom 或特定生成器
// 这里演示旧版常用方式,新版建议查看文档迁移到 TextRandomGenerator
/*
RandomStringGenerator generator = new RandomStringGenerator.Builder()
.withinRange('a', 'z').build();
System.out.println(generator.generate(10));
*/
}
}
6. 其他专业模块简述
A. Commons Math (commons-math3 / commons-numbers)
用于科学计算。
// 统计示例
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
DescriptiveStatistics stats = new DescriptiveStatistics();
stats.addValue(10); stats.addValue(20); stats.addValue(30);
System.out.println("Mean: " + stats.getMean()); // 平均值
System.out.println("StdDev: " + stats.getStandardDeviation()); // 标准差
B. Commons CLI (commons-cli:commons-cli)
解析命令行参数。
import org.apache.commons.cli.*;
Options options = new Options();
options.addOption("p", "port", true, "Server port");
options.addOption("h", "help", false, "Print help");
CommandLineParser parser = new DefaultParser();
try {
CommandLine cmd = parser.parse(options, new String[]{"-p", "8080", "-h"});
if (cmd.hasOption("help")) {
// 打印帮助
}
String port = cmd.getOptionValue("port"); // "8080"
} catch (ParseException e) {
e.printStackTrace();
}
C. Commons Pool (commons-pool2)
对象池化技术,是数据库连接池(如 DBCP)的基础。
// 自定义对象工厂,实现 PooledObjectFactory 接口
// 创建 GenericObjectPool<MyObject> pool = new GenericObjectPool<>(factory);
// MyObject obj = pool.borrowObject();
// pool.returnObject(obj);
💡 最佳实践与注意事项
-
版本选择:
- 始终使用 Commons Lang 3.x (包名
org.apache.commons.lang3),不要使用过时的 Lang 2.x。 - Collections 请使用 4.x。
- IO 请使用 2.x。
- 始终使用 Commons Lang 3.x (包名
-
性能考量:
FileUtils和IOUtils内部做了缓冲优化,通常比手写裸流快且不易出错。Reflections或BeanUtils在高频循环中会有性能损耗,建议在初始化阶段使用,或使用缓存。
-
依赖冲突:
- Commons 组件之间依赖较少,但要注意传递依赖。例如,某些旧框架可能依赖
commons-lang:2.6,而你的项目用3.12.0,Maven 通常会处理,但在复杂构建中需检查dependency:tree。
- Commons 组件之间依赖较少,但要注意传递依赖。例如,某些旧框架可能依赖
-
Java 新特性的替代:
StringUtilsvsStringmethods: JDK 11+ 引入了isBlank,strip,部分替代了 Lang。IOUtilsvsFiles: JDK 7+ 的Files.readAllBytes,Files.copy已经很强,但IOUtils在处理InputStream到Writer这种跨类型转换时依然更方便。CollectionUtilsvsStream: Java 8 Stream API 可以完成大部分集合运算,但intersection,subtract等特定集合论操作,Commons 依然更直观。
总结
Apache Commons 是 Java 程序员的“瑞士军刀”。
- 日常开发必引:Lang, IO, Collections。
- Web/框架开发必引:BeanUtils, Codec。
- 特定领域按需引入:Math, CLI, Configuration, Pool。
掌握这些组件,能让你的代码减少 30% 的样板代码(Boilerplate),提高可读性和健壮性。
本文来自博客园,作者:蓝迷梦,转载请注明原文链接:https://www.cnblogs.com/hewei-blogs/articles/19739482

浙公网安备 33010602011771号