目录
Commons Lang3 概述
1、标准 java 库无法提供足够的方法来操作其核心类,apache commons lang 子项目提供了这些额外的方法。特别是字符串操作方法、基本数值方法、对象反射、并发、创建和序列化以及系统属性。经理再也不用担心空指针异常。此外 lang 还还包含对 java.util.date 的基本增强,以及一系列专门用于帮助构建方法的实用程序,如 hasHcode、toString 和 equals。
2、lang3.0(及其后续版本)使用的包(org.apache.commons.lang3)与以前的版本(org.apache.commons.lang)不同,允许它与以前的版本同时使用。
3、Apache Commons Lang3 子项目官网地址:Lang – Home
4、Apache Commons Lang3 二进制包下载地址:Lang – Download Apache Commons Lang
5、Apache Commons Lang3 Maven 依赖:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
6、Apache Commons Lang 3.9 API 文档:Apache Commons Lang 3.11 API
Commons lang3 常用工具类
工具类 | 描述 | 示例 |
---|---|---|
org.apache.commons.lang3.ObjectUtils | 对象工具类 | ObjectUtils.isNotEmpty(new int[]{}) = false |
org.apache.commons.lang3.math.NumberUtils | 数值工具类 | NumberUtils.toInt(null) = 0, NumberUtils.toInt("1") = 1 |
org.apache.commons.lang3.ArrayUtils | 数组工具类 | ArrayUtils.remove([1, 0], 1) = [1] |
org.apache.commons.lang3.BooleanUtils | 布尔工具类 | BooleanUtils.toInteger(true) = 1, BooleanUtils.toBoolean(1) = Boolean.TRUE |
org.apache.commons.lang3.RandomStringUtils | 随机字符串工具类 | RandomStringUtils.randomAlphabetic(10) = "CtDdCZEldF", RandomStringUtils.randomGraph(10) = #vdP\eCl@F |
org.apache.commons.lang3.RandomUtils | 随机数值工具类 | RandomUtils.nextBoolean(), RandomUtils.nextInt(100,1000) |
org.apache.commons.lang3.SystemUtils | 系统工具类 | SystemUtils.getUserHome() = "C:\Users\Think" |
org.apache.commons.lang3.time.DateFormatUtils | 日期格式化工具类,将日期转为指定格式的字符串 | DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:dd") = "2019-11-11 11:11:11" |
org.apache.commons.lang3.time.DateUtils | 日期工具类,将指定格式的字符串转为日期 | DateUtils.parseDate("1993-09-08 14:30:08","yyyy-MM-dd HH:mm:dd") |
org.apache.commons.lang3.time.StopWatch | 秒表,计时器 |
StringUtils 工具类方法汇总
更多详细内容,参考官网。
src/main/java/com/wmx/apachestudy/lang/StringUtilsTest.java · 汪少棠/apache-study - Gitee.com
RandomUtils 工具类方法汇总
底层也是使用 java.util.Random。
方法 | 描述 | |
---|---|---|
static int nextInt() | 生成 [0, Integer.MAX_VALUE) 之间的随机 int 值 | |
static int nextInt(final int startInclusive, final int endExclusive) | 生成 [startInclusive,endExclusive) 之间的随机整数,起始值不能小于终止值。 | |
static boolean nextBoolean() | 随机生成一个布尔值,true 或者 false | |
static long nextLong() | 生成 [0, Long.MAX_VALUE) 之间的 long 值 | |
long nextLong(final long startInclusive, final long endExclusive) | 生成 [startInclusive,endExclusive) 之间的随机 long 值 | |
static byte[] nextBytes(final int count) | 生成指定个数的字节数组,如 nextBytes(10) 生成的字节数组有 10 个 byte 元素 | |
static double nextDouble() | 生成 [0, Double.MAX_VALUE) 直接的随机 double 值 | |
double nextDouble(final double startInclusive, final double endInclusive) | 生成 [startInclusive,endExclusive) 之间的随机 double 值 | |
static float nextFloat() | 生成 [0, Float.MAX_VALUE) 之间的随机 fluat 值 | |
float nextFloat(final float startInclusive, final float endInclusive) | 生成 [startInclusive,endExclusive) 之间的随机 float 值 |
RandomStringUtils 随机字符串
random(final int count) | 创建长度为指定个数(count)的随机字符串,将从所有字符集中选择字符,不含字母和数字,如 "篊𣶇ࢦ𣿎椗彩𩬉𦿣𦃹뢂垅" |
random(final int count, final boolean letters, final boolean numbers) | 生成指定个数(count)的随机字符串,字符将从参数指示的字母或数字字符集中选择. 1、letters: 字母字符集、numbers:数字字符集 |
random(final int count, final char... chars) | 创建长度为指定个数的随机字符串,从指定的字符集(chars)中选择字符. chars 的个数可以小于 count |
random(final int count, final String chars): | 从指定的字符集中选择字符生成指定个数的随机字符串 |
randomAlphabetic(final int count) | 创建指定长度的随机字符串,字符将从 (a-z, A-Z) 中选择,等同于 random(count, true, false) |
randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) | 创建长度介于 [minLengthInclusive,maxLengthExclusive) 之间的随机字符串 randomAlphanumeric(final int count):创建长度为指定字符数的随机字符串,从拉丁字母字符集(a-z, A-Z)和数字0-9中选择,等同于 random(count, true, true) |
randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) | 创建长度介于 [minLengthInclusive,maxLengthExclusive) 之间的随机字符串 |
randomAscii(final int count) | 随机字符将从 ASCII 码值介于 [32,126] 之间的字符集中选择,等价于:random(count, 32, 127, false, false) |
randomAscii(final int minLengthInclusive, final int maxLengthExclusive) | 创建的随机字符串个数介于 [minLengthInclusive,maxLengthExclusive) |
randomGraph(final int count) | 随机字符从所有可见的 ASCII 字符中选择,即除空格和控制字符外的任何内容,等价于:random(count, 33, 126, false, false) |
randomGraph(final int minLengthInclusive, final int maxLengthExclusive) | randomNumeric(final int count): 创建长度为指定字符数的随机字符串,随机字符将从数字字符集中选择。 |
randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) | randomPrint(final int count): 随机字符从所有可见的 ASCII 码字符和空格(即除控制字符外的任何内容)中选择。等价于 random(count, 32, 126, false, false) |
在线练习源码:src/main/java/com/wmx/apachestudy/lang/RandomStringTest.java · 汪少棠/apache-study - Gitee.com
ObjectUtils 对象工具类
方法 | 举例 | |
allNotNull(final Object... values) 检查给定数组中的任何元素值是否都不是 null。 | ObjectUtils.allNotNull(*) = true | ObjectUtils.allNotNull(null, null) = false ObjectUtils.allNotNull(null, *) = false ObjectUtils.allNotNull(*, null) = false ObjectUtils.allNotNull(*, *, null, *) = false |
anyNotNull(final Object... values) 检查给定数组中的元素是否有不是 null 的值。 | ObjectUtils.anyNotNull(*) = true | ObjectUtils.anyNotNull(null, null, *, *) = true ObjectUtils.anyNotNull(null) = false ObjectUtils.anyNotNull(null, null) = false |
clone(final T obj) | 克隆对象。如果 obj 为 null,则返回 null. | |
cloneIfPossible(final T obj): | 先调 clone(final T obj) ,如果返回 null,则返回原来的 obj 对象. | |
compare(final T c1, final T c2) compare(final T c1, final T c2, final boolean nullGreater) | 1、如果 c1 < c2,则返回负数;如果 c1 > c2,则返回正数;如果 c1 = c2,则返回 0; 2、c1、c2 可以为 null。nullGreater 为 false 时,先判断 c1 如果 null ,则返回 -1,再判断 c2 如果为 null,则返回 1. 3、compare(final T c1, final T c2) 底层是 compare(c1, c2, false) | |
T defaultIfNull(final T object, final T defaultValue) 如果传递的对象是 null,则返回默认值 | ObjectUtils.defaultIfNull(null, null) = null ObjectUtils.defaultIfNull(null, "") = "" ObjectUtils.defaultIfNull(null, "zz") = "zz" | ObjectUtils.defaultIfNull("abc", *) = "abc" ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE |
firstNonNull(final T... values) 返回数组中不是 null 的第一个值 | ObjectUtils.firstNonNull(null, null) = null ObjectUtils.firstNonNull(null, "") = "" ObjectUtils.firstNonNull(null, null, "") = "" ObjectUtils.firstNonNull(null, "zz") = "zz" | ObjectUtils.firstNonNull("abc", *) = "abc" ObjectUtils.firstNonNull(null, "xyz", *) = "xyz" ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE ObjectUtils.firstNonNull() = null |
isEmpty(final Object object) 检查对象是否为空,支持:CharSequence、Array、Collection、Map | ObjectUtils.isEmpty(null) = true ObjectUtils.isEmpty("") = true ObjectUtils.isEmpty("ab") = false | ObjectUtils.isEmpty(new int[]{}) = true ObjectUtils.isEmpty(new int[]{1,2,3}) = false ObjectUtils.isEmpty(1234) = false |
isNotEmpty(final Object object) | ObjectUtils.isNotEmpty(null) = false ObjectUtils.isNotEmpty("") = false ObjectUtils.isNotEmpty("ab") = true | ObjectUtils.isNotEmpty(new int[]{}) = false ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true ObjectUtils.isNotEmpty(1234) = true |
max(final T... values):获取其中最大的值 min(final T... values): 获取其中最小的值 median(final T... items):获取其中的中位数 |
在线练习源码:src/main/java/com/wmx/apachestudy/lang/ObjectUtilsStudy.java · 汪少棠/apache-study - Gitee.com
NumberUtils 数值工具类
1、常用常量如下:
Long LONG_ZERO = Long.valueOf(0L); Long LONG_ONE = Long.valueOf(1L); Long LONG_MINUS_ONE = Long.valueOf(-1L); Integer INTEGER_ZERO = Integer.valueOf(0); Integer INTEGER_ONE = Integer.valueOf(1); Integer INTEGER_TWO = Integer.valueOf(2); Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); Short SHORT_ZERO = Short.valueOf((short) 0); Short SHORT_ONE = Short.valueOf((short) 1); Short SHORT_MINUS_ONE = Short.valueOf((short) -1); | Byte BYTE_ZERO = Byte.valueOf((byte) 0); Byte BYTE_ONE = Byte.valueOf((byte) 1); Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); Double DOUBLE_ZERO = Double.valueOf(0.0d); Double DOUBLE_ONE = Double.valueOf(1.0d); Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); Float FLOAT_ZERO = Float.valueOf(0.0f); Float FLOAT_ONE = Float.valueOf(1.0f); Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); |
2、常用方法如下:
int compare(final byte x, final byte y):比较 x、y 的大小,源码: return x - y; int compare(final int x, final int y): 比较 x、y 的大小,源码:x == y ? 0 : x < y ? -1 : 1 int compare(final long x, final long y): 比较 x、y 的大小,源码:x == y ? 0 : x < y ? -1 : 1 int compare(final short x, final short y) : 比较 x、y 的大小,源码:x == y ? 0 : x < y ? -1 : 1 | |
BigInteger createBigInteger(final String str) 1、将字符串转成 BigInteger,支持 10进制,十六进制(以0X或者#开头)、8进制(以0开头) 2、如果 str 为 null,则返回 null。如果转换错误,则抛出 NumberFormatException | |
BigDecimal createBigDecimal(final String str) 1、将字符串转成 BigDecimal,只支持 10 进制,底层就是使用 new BigDecimal(str) 2、str 为null时,返回 null,str 为空时会抛出 NumberFormatException 异常 | |
Double createDouble(final String str):字符串转 Double 类型,源码: str == null ? null : Double.valueOf(str); Float createFloat(final String str):字符串转 Float 类型,源码: str == null ? null : Float.valueOf(str); Integer createInteger(final String str):1、字符串转 Integer 类型,支持十六进制(0xhhhh)、8进制(0dddd),源码: str == null ? null : Integer.decode(str); Long createLong(final String str):1、字符串转 Long 类型,支持十六进制(0xhhhh)、8进制(0dddd),源码: str == null ? null : Long.decode(str); | |
boolean isCreatable(final String str) 1、判断字符串是否为有效的 java 数字,支持16进制、8进制、10进制、正数负数、科学计数法(如8.788006e+05)、类型限定符(110L、3.14f) 2、0X 开头当做 16 进制处理,如 0X89F9;以0开头的非十六进制字符串作为八进制值处理,如 076、-076等 3、注意例如 098 不是八进制,因为8进制是0-7,没有8、9,所以会当做10进制处理,而此时不是数字,所以为false. 4、str 为空或者为 null,都返回 false | |
boolean isDigits(final String str) 1、检查字符串中是否只含有数字,负数和小数都会返回 false 2、str 为 null 或者为空 返回 false 3、底层调用 {@link StringUtils#isNumeric(java.lang.CharSequence)} | |
boolean isParsable(final String str) 1、检查字符串是否可以解析为数字,即 {@link Integer#parseInt(String)},{@link Long#parseLong(String)}, {@link Float#parseFloat(String),{@link Double#parseDouble(String)}. 2、这个方法可以防止调用上面的方法时出现 {@link java.text.ParseException} 3、注意只支持 10 进制,支持正负数,支持小数,支持不 8进制、16进制、不支持科学计数法,也不支持类型限定符(如 3000L,3.14F) | |
求最大值 byte max(final byte... array) | 求最小值 byte min(byte a, final byte b, final byte c) byte min(final byte... array) double min(final double a, final double b, final double c) double min(final double... array) float min(final float a, final float b, final float c) float min(final float... array) int min(int a, final int b, final int c) int min(final int... array) long min(long a, final long b, final long c) long min(final long... array) short min(short a, final short b, final short c) short min(final short... array) |
byte toByte(final String str):字符串转 byte,如果转换失败,异常捕获后不会抛出,直接返回默认值0;如果 str 为 null,则返回默认值 0 其它数值类型也是同理(转换失败不会抛出异常,而是返回默认值) | 其它数值类型也是同理(转换失败不会抛出异常,而是返回默认值) float toFloat(final String str, final float defaultValue) int toInt(final String str): long toLong(final String str): toInt(final String str, final int defaultValue) long toLong(final String str, final long defaultValue) short toShort(final String str) toShort(final String str, final short defaultValue) |
在线源码:src/main/java/com/wmx/apachestudy/lang/NumberUtilsTest.java · 汪少棠/apache-study - Gitee.com
ArrayUtils 通用数组操作工具类
1、有了封装的工具类,可以对数组如同 List 一样进行增删改查,而且可以有效的避免空指针异常。
在线演示源码:
src/main/java/com/wmx/apachestudy/lang/ArrayUtilsTest.java · 汪少棠/apache-study - Gitee.com
更多 API 方法可以参考官网文档:Apache Commons Lang 3.11 API
ExceptionUtils 异常工具类
1、ExceptionUtils 代替原生的 e.printStackTrace() 打印日志,防止在在高并发下获取异常信息阻塞,提供性能。
2、比如新增保存数据,主键冲突,如果直接使用 e.getMessage() ,则获取的是:java.lang.RuntimeException: SQL Exception:insert into xxx(a,b,c) values(1,2,3,)
没有办法获取到底层的堆栈信息:oracle.jdbc.OracleDatabaseException: ORA-00001: 违反唯一约束条件(xxx).
而使用 ExceptionUtils.getStackTrace(e) 则可以获取整个堆栈信息.
/**
* String getStackTrace(final Throwable throwable): 以字符串形式从可丢弃对象获取堆栈跟踪信息
*/
@Test
public void testGetStackTrace() {
try {
System.out.println(1 / 0);
} catch (Exception e) {
String stackTrace = ExceptionUtils.getStackTrace(e);
System.out.println(stackTrace);
}
try {
int[] ints = {1, 2, 3};
System.out.println(ints[8]);
} catch (Exception e) {
e.getMessage();
String stackTrace = ExceptionUtils.getStackTrace(e);
System.out.println(stackTrace);
}
}
Pair 对象对 与 Triple 三元对象组
1、当一个方法需要返回两个及以上字段时,通常是封装成一个临时对象,比如 Map 返回,现在有了 Pair 和 Triple 就不需要了。一般来说,元组适用于临时数据传递和返回多值的情况。
2、Pair 可以同时封装两个对象,Triple 可以同时封装三个对象。
/**
* MutableTriple:可变三元对象组,里面有 left、middle、right 三个元素,用于封装三个对象。
* MutableTriple 是可变的,构建对象后,可以再 setXxx 修改值
* 如果其中的元素对象都是线程安全的,则是线程安全的。
*/
@Test
public void mutableTriple() {
// 同时封装 3 个对象
MutableTriple<Integer, String, Date> mutableTriple = MutableTriple.of(212, "蚩尤后裔", new Date());
mutableTriple.setLeft(800);
//800,蚩尤后裔,Sun Jun 13 09:27:37 CST 2021
System.out.println(mutableTriple.getLeft() + "," + mutableTriple.getMiddle() + "," + mutableTriple.getRight());
}
3、在线演示源码:src/main/java/com/wmx/apachestudy/lang/PairTest.java · 汪少棠/apache-study - Gitee.com
4、还有一个库叫 javatuples,它直接支持 2元组到10元组。
StopWatch 秒表
createStarted() :创建新的秒表并启动. boolean isSuspended():判断秒表是否处于暂停. String toString():获取开始到调用此方法的时间,或者是从开始到停止的时间量,如 00:00:01.203,格式:时:分:秒.毫秒 |
在线演示源码:/src/main/java/com/wmx/apachestudy/time/StopWatchTest.java
StringEscapeUtils 字符串转义
1、StringEscapeUtils最初是Apache Commons Lang库的一部分(2.0版本引入),用于处理字符串的转义与反转义。由于模块化调整,自Commons Lang 3.6起,该类被标记为过时并迁移至Commons Text包。该类所有方法均为静态且线程安全,无需实例化即可直接调用。
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.17.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.13.0</version>
</dependency>
/**
* HTML转义(防止XSS攻击) & 反转义
*/
@Test
public void testHtmlEscape() throws Exception {
String escapedHtml = StringEscapeUtils.escapeHtml4("<script>alert('xss')</script>");
// <script>alert('xss')</script>
System.out.println(escapedHtml);
String original = StringEscapeUtils.unescapeHtml4(escapedHtml);
// <script>alert('xss')</script>
System.out.println(original);
}
src/main/java/com/wmx/apachestudy/lang/StringEscapeUtilsTest.java · 汪少棠/apache-study - Gitee.com。