Apache Commons Lang 是一个流行的 Java 实用工具库,其中 commons-lang3
是其最新的主流版本,用于增强 Java 核心功能,特别是对 java.lang
包的扩展。以下是 commons-lang3
的功能概述,以及如何使用其中的一些工具(如 RegExUtils
)。
Maven 依赖
在使用 commons-lang3
之前,需要在项目中添加 Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- 或最新版本 -->
</dependency>
主要工具与功能
1. StringUtils
- 提供对字符串操作的各种实用方法。
import org.apache.commons.lang3.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = " Hello World ";
// 判断字符串是否为空或空白
System.out.println(StringUtils.isBlank(str)); // false
// 删除两端空格
System.out.println(StringUtils.trim(str)); // "Hello World"
// 反转字符串
System.out.println(StringUtils.reverse(str)); // " dlroW olleH "
}
}
2. RegExUtils
- 用于处理正则表达式的高级工具。
import org.apache.commons.lang3.RegExUtils;
public class RegExUtilsExample {
public static void main(String[] args) {
String text = "key1:value1, key2:value2, key3:value3";
// 替换冒号为下划线
String result = RegExUtils.replaceAll(text, ":", "_");
System.out.println(result); // "key1_value1, key2_value2, key3_value3"
}
}
3. NumberUtils
- 提供数字操作的工具方法。
import org.apache.commons.lang3.math.NumberUtils;
public class NumberUtilsExample {
public static void main(String[] args) {
// 判断是否是数字
System.out.println(NumberUtils.isCreatable("123")); // true
System.out.println(NumberUtils.isCreatable("12.3")); // true
System.out.println(NumberUtils.isCreatable("abc")); // false
// 找到数组中的最大值
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(NumberUtils.max(numbers)); // 5
}
}
4. DateUtils
- 提供日期和时间操作的工具。
import org.apache.commons.lang3.time.DateUtils;
import java.text.ParseException;
import java.util.Date;
public class DateUtilsExample {
public static void main(String[] args) throws ParseException {
String dateStr = "2025-01-01";
// 解析日期
Date date = DateUtils.parseDate(dateStr, "yyyy-MM-dd");
System.out.println(date);
// 添加天数
Date newDate = DateUtils.addDays(date, 5);
System.out.println(newDate);
}
}
5. RandomStringUtils
- 生成随机字符串的工具。
import org.apache.commons.lang3.RandomStringUtils;
public class RandomStringUtilsExample {
public static void main(String[] args) {
// 生成随机字母字符串
String randomAlphabetic = RandomStringUtils.randomAlphabetic(10);
System.out.println(randomAlphabetic);
// 生成随机数字字符串
String randomNumeric = RandomStringUtils.randomNumeric(10);
System.out.println(randomNumeric);
}
}
6. ObjectUtils
- 提供对对象操作的工具。
import org.apache.commons.lang3.ObjectUtils;
public class ObjectUtilsExample {
public static void main(String[] args) {
String str = null;
// 如果对象为 null,提供默认值
System.out.println(ObjectUtils.defaultIfNull(str, "Default Value")); // "Default Value"
// 判断多个对象是否都不为空
System.out.println(ObjectUtils.allNotNull("A", "B", "C")); // true
System.out.println(ObjectUtils.allNotNull("A", null, "C")); // false
}
}
总结
commons-lang3
提供了一系列增强 Java 核心功能的工具类,常用功能包括:
- 字符串处理:
StringUtils
、RegExUtils
- 数字操作:
NumberUtils
- 日期操作:
DateUtils
- 随机字符串生成:
RandomStringUtils
- 对象工具:
ObjectUtils