org.apache.commons.lang3都有什么常用的类
org.apache.commons.lang3是 Apache Commons Lang 库的核心包,提供了很多实用的工具类。以下是常用的类及示例说明:
1. StringUtils - 字符串工具类
// 空值安全处理
String str = null;
StringUtils.isEmpty(str); // true
StringUtils.isBlank(" "); // true
StringUtils.defaultIfBlank(str, "default"); // "default"// 字符串操作
StringUtils.substring("hello", 1, 3); // "el"
StringUtils.join(new String[]{"a", "b"}, ","); // "a,b"
StringUtils.repeat("ab", 2); // "abab"2. ArrayUtils - 数组工具类
// 数组操作
int[] arr = {1, 2, 3};
int[] newArr = ArrayUtils.add(arr, 4); // [1,2,3,4]
boolean contains = ArrayUtils.contains(arr, 2); // true
int[] empty = ArrayUtils.EMPTY_INT_ARRAY; // 空数组3. DateUtils - 日期工具类
// 日期计算
Date now = new Date();
Date tomorrow = DateUtils.addDays(now, 1);
Date sameDayNextMonth = DateUtils.addMonths(now, 1);// 日期比较(忽略时间部分)
boolean sameDay = DateUtils.isSameDay(date1, date2);4. NumberUtils - 数字工具类
// 数字转换和比较
NumberUtils.toInt("123", 0); // 123,转换失败返回默认值0
NumberUtils.max(1, 3, 2); // 3
NumberUtils.isDigits("123"); // true5. BooleanUtils - 布尔工具类
// 布尔值转换
BooleanUtils.toBooleanObject("yes"); // Boolean.TRUE
BooleanUtils.negate(true); // false
BooleanUtils.toStringOnOff(true); // "on"6. ObjectUtils - 对象工具类
// 空值安全处理
String result = ObjectUtils.defaultIfNull(str, "default");
ObjectUtils.firstNonNull(null, null, "value"); // "value"7. RandomStringUtils - 随机字符串生成
// 生成随机字符串
RandomStringUtils.randomAlphabetic(10); // 10位字母
RandomStringUtils.randomNumeric(6); // 6位数字
RandomStringUtils.randomAlphanumeric(8); // 8位字母数字8. Validate - 参数验证
// 参数校验
Validate.notNull(obj, "对象不能为空");
Validate.isTrue(age > 0, "年龄必须大于0: %d", age);
Validate.notEmpty(collection, "集合不能为空");9. SystemUtils - 系统工具
// 系统信息
SystemUtils.IS_OS_WINDOWS; // 是否Windows系统
SystemUtils.JAVA_HOME; // Java安装目录
SystemUtils.USER_HOME; // 用户主目录10. ToStringBuilder - 对象toString
public class Person {private String name;private int age;@Overridepublic String toString() {return new ToStringBuilder(this).append("name", name).append("age", age).toString();}
}11. EqualsBuilder/HashCodeBuilder
// 重写equals和hashCode
@Override
public boolean equals(Object obj) {return EqualsBuilder.reflectionEquals(this, obj);
}@Override
public int hashCode() {return HashCodeBuilder.reflectionHashCode(this);
}12. StopWatch - 计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 执行任务...
stopWatch.stop();
System.out.println("耗时: " + stopWatch.getTime() + "ms");这些工具类大大提高了开发效率,减少了重复代码的编写,是Java开发中非常实用的辅助工具。
