@File
2020-04-30T05:57:07.000000Z
字数 90172
阅读 438
java

相关连接
依赖
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.8.1</version></dependency>
lang3 常规工具类
static add() 数组添加元素
String[] strs1 = {"李"};// 添加"大爷"进数组中String[] strs2 = ArrayUtils.add(strs1, "大爷");// 结果:[李]System.out.println(Arrays.asList(strs1));// 结果:[李, 大爷]System.out.println(Arrays.asList(strs2));
static addAll() 数组批量添加元素
String[] strs1 = {"李"};String[] strs2 = {"大","爷"};// 结果:[李, 大, 爷]System.out.println(Arrays.asList(ArrayUtils.addAll(strs1,strs2)));// 结果:[李, 学, 霸]System.out.println(Arrays.asList(ArrayUtils.addAll(strs1,"学","霸")));
static clone() 克隆数组
String[] strs1 = {"李",null,""};// 结果:[李, null, ]System.out.println(Arrays.asList(ArrayUtils.clone(strs1)));
static contains() 是否在数组中
String[] strs1 = {"李","大","爷"};// 结果:falseSystem.out.println(ArrayUtils.contains(strs1,null));// 结果:trueSystem.out.println(ArrayUtils.contains(strs1,"大"));
static getLength() 取数组长度
String[] strs1 = {"李","大","爷"};// 结果:0System.out.println(ArrayUtils.getLength(null));// 结果:3System.out.println(ArrayUtils.getLength(strs1));
static hashCode() 取哈希码
String[] strs1 = {"李","大","爷"};// 结果:629System.out.println(ArrayUtils.hashCode(null));// 结果:37939365System.out.println(ArrayUtils.hashCode(strs1));
static indexOf() 取指定元素的下标
String[] strs1 = {"李","大","爷"};// 结果:1System.out.println(ArrayUtils.indexOf(strs1,"大"));// 结果:-1System.out.println(ArrayUtils.indexOf(strs1,null));
static lastIndexOf() 取指定元素的最后一个下标static insert() 元素插入到数组指定位置
String[] strs1 = {"李","大","爷"};// 结果:[李, 学, 霸, 大, 爷]System.out.println(Arrays.asList(ArrayUtils.insert(1,strs1, "学","霸")));
static isArrayIndexValid() 数组下标是否有效
String[] strs1 = {"李",null,"爷"};// 结果:falseSystem.out.println(Arrays.asList(ArrayUtils.isArrayIndexValid(strs1,3)));// 结果:trueSystem.out.println(Arrays.asList(ArrayUtils.isArrayIndexValid(strs1,2)));// 结果:trueSystem.out.println(Arrays.asList(ArrayUtils.isArrayIndexValid(strs1,1)));
static isEmpty() 是否为空数组
String[] strs1 = {"李","大","爷"};String[] strs2 = {null};String[] strs3 = {};// 结果:falseSystem.out.println(ArrayUtils.isEmpty(strs1));// 结果:falseSystem.out.println(ArrayUtils.isEmpty(strs2));// 结果:trueSystem.out.println(ArrayUtils.isEmpty(strs3));
static isNotEmpty() 是否不为空数组static isSameLength() 两个数组长度是否一样
String[] strs1 = {"李","大","爷"};String[] strs2 = {"胡","大","妈"};String[] strs3 = {null};String[] strs4 = {};// 结果:falseSystem.out.println(ArrayUtils.isSameLength(strs3,strs4));// 结果:trueSystem.out.println(ArrayUtils.isSameLength(strs1,strs2));// 结果:trueSystem.out.println(ArrayUtils.isSameLength(null,strs4));
static isSameType() 两个数组类型是否一样
String[] strs1 = {"李","大","爷"};String[] strs2 = {};// 结果:trueSystem.out.println(ArrayUtils.isSameType(strs1,strs2))// 报错!System.out.println(ArrayUtils.isSameType(strs1,null));
static isSorted() 数组是否根据自然排序
String[] strs1 = {"李","大","爷"};// 结果:falseSystem.out.println(ArrayUtils.isSorted(strs1));// 排序Arrays.sort(strs1);// 结果:trueSystem.out.println(ArrayUtils.isSorted(strs1));
static nullToEmpty() 空数组转换
String[] strs = null;// 结果:[]System.out.println(Arrays.asList(ArrayUtils.nullToEmpty(strs)));
static remove() 移除指定位置元素
String[] strs = {"李","大","爷"};// 结果:[李, 爷]System.out.println(Arrays.asList(ArrayUtils.remove(strs,1)));// 报错!System.out.println(Arrays.asList(ArrayUtils.remove(strs,3)));
static removeAll() 移除指定位置元素(多个)
String[] strs = {"李","大","爷"};// 结果:[李]System.out.println(Arrays.asList(ArrayUtils.removeAll(strs,1,2)));// 报错!System.out.println(Arrays.asList(ArrayUtils.removeAll(strs,1,3)));
static removeAllOccurences() 移除指定元素(全部)
String[] strs = {"李","大","爷","大"};// 结果:[李, 爷]System.out.println(Arrays.asList(ArrayUtils.removeAllOccurences(strs,"大")));
statuc removeElement() 移除指定元素(第一个)
String[] strs = {"李","大","爷","大"};// 结果:[李, 爷, 大]System.out.println(Arrays.asList(ArrayUtils.removeElement(strs,"大")));
static removeElements() 移除指定元素(多个)
String[] strs = {"李","大","爷","大"};// 结果:[李, 大]System.out.println(Arrays.asList(ArrayUtils.removeElements(strs,"大","爷")));// 结果:[李, 爷]System.out.println(Arrays.asList(ArrayUtils.removeElements(strs,"大","大")));
static reverse() 反转数组
String[] strs1 = {"李","大","爷"};String[] strs2 = {"李","大","爷"};String[] strs3 = {"李","大","爷"};// 反转ArrayUtils.reverse(strs1);ArrayUtils.reverse(strs2,1,2);ArrayUtils.reverse(strs2,1,3);// 结果:[爷, 大, 李]System.out.println(Arrays.asList(strs1));// 结果:[李, 爷, 大]System.out.println(Arrays.asList(strs2));// 结果:[李, 大, 爷]System.out.println(Arrays.asList(strs3));
static shift() 元素顺序偏移
String[] strs1 = {"李","大","爷"};String[] strs2 = {"李","大","爷"};// 后移两位ArrayUtils.shift(strs1,2);// 前移一位ArrayUtils.shift(strs2,-1);// 结果:[大, 爷, 李]System.out.println(Arrays.asList(strs1));// 结果:[大, 爷, 李]System.out.println(Arrays.asList(strs2));
static shuffle() 元素顺序打乱
String[] strs = {"李","大","爷"};// 第一次ArrayUtils.shuffle(strs);// 结果: [李, 爷, 大]System.out.println(Arrays.asList(strs));// 第二次ArrayUtils.shuffle(strs);// 结果: [爷, 李, 大]System.out.println(Arrays.asList(strs));
static subarray() 数组截取
String[] strs = {"李","大","爷"};// 截取下标1~2,结果:[大, 爷]System.out.println(Arrays.asList(ArrayUtils.subarray(strs,1,3)));
static swap() 两个位置的元素调换位置
String[] strs = {"李","大","爷"};// 调换小标0和1的元素ArrayUtils.swap(strs,0,1);// 结果:[大, 李, 爷]System.out.println(Arrays.asList(strs));
static toArray() 生成数组
String[] strs = ArrayUtils.toArray("李", "大", "爷");
static toMap() 数组转map
String[][] strs = {{"李","大爷"},{"胡","大妈"}};// 结果:{胡=大妈, 李=大爷}System.out.println(ArrayUtils.toMap(strs));
static toObject() 转为包装类数组
int[] nums = {1,0,2,4};Integer[] integers = ArrayUtils.toObject(nums);
static toPrimitive() 转为基本数据数组
Integer[] nums = {1,0,2,4};int[] ints = ArrayUtils.toPrimitive(nums);
static toString() 转为字符串
int[] nums = {1,0,2,4};// 结果:{1,0,2,4}System.out.println(ArrayUtils.toString(nums));// 结果:{}System.out.println(ArrayUtils.toString(null));// 设置备选项,结果:李大爷牛逼System.out.println(ArrayUtils.toString(null,"李大爷牛逼"));
static toStringArray() 元素转为字符串
Integer[] nums1 = {1,0,2,4};Integer[] nums2 = {1,0,2,4,null};// 结果:[1, 0, 2, 4]System.out.println(Arrays.asList(ArrayUtils.toStringArray(nums1)));// 设置备选值,结果:[1, 0, 2, 4, 李大爷牛逼]System.out.println(Arrays.asList(ArrayUtils.toStringArray(nums2,"李大爷牛逼")));// 报错!System.out.println(Arrays.asList(ArrayUtils.toStringArray(null,"李大爷牛逼")));
static and() bool 数组中是否都为真
boolean[] arr1 = {true,false,true};boolean[] arr2 = {true,true,true};// 结果:falseSystem.out.println(BooleanUtils.and(arr1));// 结果:trueSystem.out.println(BooleanUtils.and(arr2));
static compare() bool 比较
// 结果:0System.out.println(BooleanUtils.compare(true,true));// 结果:1System.out.println(BooleanUtils.compare(true,false));// 结果:-1System.out.println(BooleanUtils.compare(false,true));
static isFalse() 是否为 false
// 结果:trueSystem.out.println(BooleanUtils.isFalse(false));// 结果:falseSystem.out.println(BooleanUtils.isFalse(true));
static isNotFalse() 是否不为 false
// 结果:falseSystem.out.println(BooleanUtils.isNotFalse(false));// 结果:trueSystem.out.println(BooleanUtils.isNotFalse(true));
static isTrue() 是否为 true
// 结果:falseSystem.out.println(BooleanUtils.isTrue(false));// 结果:trueSystem.out.println(BooleanUtils.isTrue(true));
static isNotTrue() 是否不为 true
// 结果:trueSystem.out.println(BooleanUtils.isNotTrue(false));// 结果:falseSystem.out.println(BooleanUtils.isNotTrue(true));
static negate() 取反
// 结果:trueSystem.out.println(BooleanUtils.negate(false));// 结果:falseSystem.out.println(BooleanUtils.negate(true));
static or() bool 数组中至少存在一个真
boolean[] arr1 = {true,false,true};boolean[] arr2 = {false,false,false};// 结果:trueSystem.out.println(BooleanUtils.or(arr1));// 结果:falseSystem.out.println(BooleanUtils.or(arr2));
static toBoolean() 转为bool
// 结果:falseSystem.out.println(BooleanUtils.toBoolean(0));// 结果:trueSystem.out.println(BooleanUtils.toBoolean(1));// 结果:falseSystem.out.println(BooleanUtils.toBoolean(""));// 结果:falseSystem.out.println(BooleanUtils.toBoolean("aaa"));
static toBooleanDefaultIfNull() 取bool结果并设置备选值
// 结果:trueSystem.out.println(BooleanUtils.toBooleanDefaultIfNull(null,true));// 结果:falseSystem.out.println(BooleanUtils.toBooleanDefaultIfNull(false,true));
static toBooleanObject() 自定义判断规则param1: 用作判断的值
param2: 为 true 的规则
param3: 为 false 的规则
param4: 为 null 的规则
// ----------- 数值判断// 基本的 0:假,结果:falseSystem.out.println(BooleanUtils.toBooleanObject(0));// 0 与 true 规则匹配成功,结果:trueSystem.out.println(BooleanUtils.toBooleanObject(0,0,2,1));// 0 先与 true 规则匹配成功,所以忽略了 null 规则,结果:trueSystem.out.println(BooleanUtils.toBooleanObject(0,0,2,0));// 1 与 null 规则匹配成功,结果:nullSystem.out.println(BooleanUtils.toBooleanObject(1,0,2,1));// 2 与 false 规则匹配成功,结果:falseSystem.out.println(BooleanUtils.toBooleanObject(2,0,2,1));// 3 匹配不到任何规则,所以这里报错了!System.out.println(BooleanUtils.toBooleanObject(3,0,2,1));// ------------ 字符串判断// 基本的 所有字符串都为:null,结果:nullSystem.out.println(BooleanUtils.toBooleanObject("李"));// 李 与 true 规则匹配成功,结果:trueSystem.out.println(BooleanUtils.toBooleanObject("李","李","大","爷"));// 大 与 false 规则匹配成功,结果:falseSystem.out.println(BooleanUtils.toBooleanObject("大","李","大","爷"));// 爷 与 null 规则匹配成功,结果:nullSystem.out.println(BooleanUtils.toBooleanObject("爷","李","大","爷"));// 啊 匹配不到任何规则,所以这里报错了!System.out.println(BooleanUtils.toBooleanObject("啊","李","大","爷"));
static toInteger() bool 转 int
// 结果:1System.out.println(BooleanUtils.toInteger(true));// 结果:0System.out.println(BooleanUtils.toInteger(false));// 结果:1System.out.println(BooleanUtils.toInteger(true,1,2));// 结果:2System.out.println(BooleanUtils.toInteger(false,1,2));// 结果:3System.out.println(BooleanUtils.toInteger(null,1,2,3));
static toIntegerObject() bool 转 Integer
// 结果:1System.out.println(BooleanUtils.toIntegerObject(true));// 结果:0System.out.println(BooleanUtils.toIntegerObject(false));// 结果:nullSystem.out.println(BooleanUtils.toIntegerObject(null));// 结果:1System.out.println(BooleanUtils.toIntegerObject(true,1,2));// 结果:2System.out.println(BooleanUtils.toIntegerObject(false,1,2));// 结果:3System.out.println(BooleanUtils.toIntegerObject(null,1,2,3));
static toString() bool 转字符串
// 结果:李System.out.println(BooleanUtils.toString(true,"李","大"));// 结果:大System.out.println(BooleanUtils.toString(false,"李","大"));// 结果:爷System.out.println(BooleanUtils.toString(null,"李","大","爷"));
static toStringOnOff() bool 转字符串(on|off|null)
// 结果:onSystem.out.println(BooleanUtils.toStringOnOff(true));// 结果:offSystem.out.println(BooleanUtils.toStringOnOff(false));// 结果:nullSystem.out.println(BooleanUtils.toStringOnOff(null));
static toStringTrueFalse() bool 转字符串(true|false|null)
// 结果:"true"System.out.println(BooleanUtils.toStringTrueFalse(true));// 结果:"false"System.out.println(BooleanUtils.toStringTrueFalse(false));// 结果:"null"System.out.println(BooleanUtils.toStringTrueFalse(null));
static toStringYesNo() bool 转字符串(yes|no|null)
// 结果:yesSystem.out.println(BooleanUtils.toStringYesNo(true));// 结果:noSystem.out.println(BooleanUtils.toStringYesNo(false));// 结果:nullSystem.out.println(BooleanUtils.toStringYesNo(null));
static xor() 给 bool 数组做异或运算
boolean[] bools1 = {true,true,false,true};boolean[] bools2 = {true,true,true};boolean[] bools3 = {true,false,false,true};// 结果:trueSystem.out.println(BooleanUtils.xor(bools1));// 结果:trueSystem.out.println(BooleanUtils.xor(bools2));// 结果:falseSystem.out.println(BooleanUtils.xor(bools3));
static subSequence() 截取一个位数后的字符串
// 结果:nullSystem.out.println(CharSequenceUtils.subSequence(null, 1));// 结果:大爷System.out.println(CharSequenceUtils.subSequence("李大爷", 1));// 报错!垃圾得很!!System.out.println(CharSequenceUtils.subSequence("李大爷", 5));
static convertClassesToClassNames() 取类列表中所有类名
List<Class<?>> clsList = new ArrayList<>(1);clsList.add(Test.class);// 结果:[com.lidaye.demo.Test]System.out.println(ClassUtils.convertClassesToClassNames(clsList));
static convertClassNamesToClasses() 取类名列表中所有类对象
List<String> list = new ArrayList<>(2);// 存在的类名list.add("com.lidaye.demo.Test");// 不存在的类名list.add("com.lidaye.demo.Demo");// 结果:[class com.lidaye.demo.Test, null]System.out.println(ClassUtils.convertClassNamesToClasses(list));
static getAbbreviatedName() 取缩写类名
// 结果:c.l.d.TestSystem.out.println(ClassUtils.getAbbreviatedName(Test.class,1));// 结果:c.l.d.TestSystem.out.println(ClassUtils.getAbbreviatedName("com.lidaye.demo.Test",1));// 结果:com.lidaye.demo.TestSystem.out.println(ClassUtils.getAbbreviatedName(Test.class,30));
static getAllInterfaces() 取类所有实现的接口接口实现及继承关系:
Test:public class Test extends TestParent implements ITest
TestParent:public class TestParent implements Serializable
ITest:public interface ITest extends ITestParent
/**结果:[interface com.lidaye.demo.ITest,interface com.lidaye.demo.ITestParent,interface java.io.Serializable]*/System.out.println(ClassUtils.getAllInterfaces(Test.class));
static getAllSuperclasses() 取类所有继承的类继承关系:
Test:public class Test extends TestParent implements ITest
TestParent:public class TestParent implements Serializable
/**结果:[class com.lidaye.demo.TestParent,class java.lang.Object]*/System.out.println(ClassUtils.getAllSuperclasses(Test.class));
static getCanonicalName() 取规范类名
// 结果:com.lidaye.demo.TestSystem.out.println(ClassUtils.getCanonicalName(Test.class));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getCanonicalName(null,"李大爷"));// 结果:com.lidaye.demo.TestSystem.out.println(ClassUtils.getCanonicalName(new Test(),"李大爷"));
static getClass() 取Class对象
// 以下结果全部为:class com.lidaye.demo.Testtry {// 默认初始化System.out.println(ClassUtils.getClass("com.lidaye.demo.Test"));// 设置为不初始化System.out.println(ClassUtils.getClass("com.lidaye.demo.Test",false));// 加入加载器System.out.println(ClassUtils.getClass(Test.class.getClassLoader(),"com.lidaye.demo.Test"));System.out.println(ClassUtils.getClass(Test.class.getClassLoader(),"com.lidaye.demo.Test",false));} catch (ClassNotFoundException e) {// 失败会报错}
static getName() 取类名
// 结果:com.lidaye.demo.TestSystem.out.println(ClassUtils.getName(Test.class));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getName(null,"李大爷"));// 结果:com.lidaye.demo.TestSystem.out.println(ClassUtils.getName(new Test(),"李大爷"));
static getPackageCanonicalName() 取包名(根据规范类名)
// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageCanonicalName(Test.class));// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageCanonicalName("com.lidaye.demo.Test"));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getPackageCanonicalName(null,"李大爷"));// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageCanonicalName(new Test(),"李大爷"));
static getPackageName() 取包名
// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageName(Test.class));// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageName("com.lidaye.demo.Test"));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getPackageName(null,"李大爷"));// 结果:com.lidaye.demoSystem.out.println(ClassUtils.getPackageName(new Test(),"李大爷"));
static getPublicMethod() 取方法
try {// 结果:public void com.lidaye.demo.Test.setName(java.lang.String)System.out.println(ClassUtils.getPublicMethod(Test.class,"setName",String.class));} catch (NoSuchMethodException e) {e.printStackTrace();}
static getShortCanonicalName() 取短规范类名
// 结果:TestSystem.out.println(ClassUtils.getShortCanonicalName(Test.class));// 结果:TestSystem.out.println(ClassUtils.getShortCanonicalName("com.lidaye.demo.Test"));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getShortCanonicalName(null,"李大爷"));// 结果:TestSystem.out.println(ClassUtils.getShortCanonicalName(new Test(),"李大爷"));
static getShortClassName() 取短类名
// 结果:TestSystem.out.println(ClassUtils.getShortClassName(Test.class));// 结果:TestSystem.out.println(ClassUtils.getShortClassName("com.lidaye.demo.Test"));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getShortClassName(null,"李大爷"));// 结果:TestSystem.out.println(ClassUtils.getShortClassName(new Test(),"李大爷"));
static getSimpleName() 取简单类名
// 结果:TestSystem.out.println(ClassUtils.getSimpleName(Test.class));// 设置了空备用值,结果:李大爷System.out.println(ClassUtils.getSimpleName(null,"李大爷"));// 结果:TestSystem.out.println(ClassUtils.getSimpleName(new Test(),"李大爷"));
static hierarchy() 获取类自身和继承的所有类对象
Iterable<Class<?>> hierarchy1 = ClassUtils.hierarchy(Test.class);// 开启扫描接口,默认是不扫描(ClassUtils.Interfaces.EXCLUDE)Iterable<Class<?>> hierarchy2 = ClassUtils.hierarchy(Test.class, ClassUtils.Interfaces.INCLUDE);/** 结果:class com.lidaye.demo.Testclass com.lidaye.demo.TestParentclass java.lang.Object*/hierarchy1.forEach(System.out::println);/** 结果:class com.lidaye.demo.Testinterface com.lidaye.demo.ITestinterface com.lidaye.demo.ITestParentclass com.lidaye.demo.TestParentinterface java.io.Serializableclass java.lang.Object*/hierarchy2.forEach(System.out::println);
static isAssignable() 类是否可自然转换
Class<?>[] clsArr1 = {Test.class,Test.class};Class<?>[] clsArr2 = {TestParent.class,Test.class};// 结果:trueSystem.out.println(ClassUtils.isAssignable(Test.class,TestParent.class));// 结果:falseSystem.out.println(ClassUtils.isAssignable(TestParent.class,Test.class));// 结果:trueSystem.out.println(ClassUtils.isAssignable(clsArr1,clsArr2));
static isInnerClass() 是否为内部类
// 结果:falseSystem.out.println(ClassUtils.isInnerClass(Test.class));// 结果:falseSystem.out.println(ClassUtils.isInnerClass(HashMap.class));// 结果:trueSystem.out.println(ClassUtils.isInnerClass(HashMap.Entry.class));
static isPrimitiveOrWrapper() 是否为基本类型或包装类
// 结果:falseSystem.out.println(ClassUtils.isPrimitiveOrWrapper(String.class));// 下面结果全都为:trueSystem.out.println(ClassUtils.isPrimitiveOrWrapper(boolean.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(Long.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(int.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(Short.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(byte.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(Double.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(float.class));System.out.println(ClassUtils.isPrimitiveOrWrapper(Character.class));
static isPrimitiveWrapper() 是否为包装类
// 结果:falseSystem.out.println(ClassUtils.isPrimitiveWrapper(String.class));// 下面结果全都为:trueSystem.out.println(ClassUtils.isPrimitiveWrapper(Boolean.class));System.out.println(ClassUtils.isPrimitiveWrapper(Long.class));System.out.println(ClassUtils.isPrimitiveWrapper(Integer.class));System.out.println(ClassUtils.isPrimitiveWrapper(Short.class));System.out.println(ClassUtils.isPrimitiveWrapper(Byte.class));System.out.println(ClassUtils.isPrimitiveWrapper(Double.class));System.out.println(ClassUtils.isPrimitiveWrapper(Float.class));System.out.println(ClassUtils.isPrimitiveWrapper(Character.class));
static primitivesToWrappers() 基本类型类数组转为包装类数组
Class<?>[] classes = ClassUtils.primitivesToWrappers(int.class, short.class, byte.class);/** 结果:[class java.lang.Integer,class java.lang.Short,class java.lang.Byte]*/System.out.println(Arrays.asList(classes));
static primitiveToWrapper() 基本类型类转包装类
// 以下结果都为:class java.lang.IntegerSystem.out.println(ClassUtils.primitiveToWrapper(int.class));System.out.println(ClassUtils.primitiveToWrapper(Integer.class));
static toClass() 取数组中对象的类
Object[] arr = {new Test(),new TestParent(),1,"李大爷"};/** 结果:[class com.lidaye.demo.Test,class com.lidaye.demo.TestParent,class java.lang.Integer,class java.lang.String]*/System.out.println(Arrays.asList(ClassUtils.toClass(arr)));
static wrappersToPrimitives() 包装类数组转成基本类型类数组
Class<?>[] arr = {Test.class,TestParent.class,Integer.class,Short.class};Class<?>[] classes1 = ClassUtils.wrappersToPrimitives(arr);// 结果:[null, null, int, short]System.out.println(Arrays.asList(classes1));
static wrapperToPrimitive() 包装类转换成基本类型类
// 结果:intSystem.out.println(ClassUtils.wrapperToPrimitive(Integer.class));
static binaryBeMsb0ToHexDigit() bool数组转char
boolean[] bools1 = {true,true,false,true};boolean[] bools2 = {true,true,false};char c1 = Conversion.binaryBeMsb0ToHexDigit(bools1);char c2 = Conversion.binaryBeMsb0ToHexDigit(bools1,1);char c3 = Conversion.binaryBeMsb0ToHexDigit(bools2);// 结果:dSystem.out.println(c1);// 结果:6System.out.println(c2);// 结果:6System.out.println(c3);
stathc binaryToByte() bool数组转byte
boolean[] bools = {true,true,false,true};byte b = Conversion.binaryToByte(bools, 1, (byte) 1, 1, 1);// 结果:3System.out.println(b);
static binaryToHexDigit() bool数组转char
boolean[] bools = {true,true,false,true};char c1 = Conversion.binaryToHexDigit(bools);char c2 = Conversion.binaryToHexDigit(bools,1);// 结果:bSystem.out.println(c1);// 结果:5System.out.println(c2);
static binaryToHexDigitMsb0_4bits() bool数组转char
boolean[] bools = {true,true,false,true,true};char c1 = Conversion.binaryToHexDigitMsb0_4bits(bools);// 数组-1必须大于4char c2 = Conversion.binaryToHexDigitMsb0_4bits(bools,1);// 结果:dSystem.out.println(c1);// 结果:bSystem.out.println(c2);
static binaryToInt() bool数组转int
boolean[] bools = {true,true,false,true};int i = Conversion.binaryToInt(bools, 1, (byte) 1, 1, 1);// 结果:3System.out.println(i);
static binaryToLong() bool数组转long
boolean[] bools = {true,true,false,true};long l = Conversion.binaryToLong(bools, 1, (byte) 1, 1, 1);// 结果:3System.out.println(l);
static binaryToShort() bool数组转short
boolean[] bools = {true,true,false,true};short s = Conversion.binaryToShort(bools, 1, (byte) 1, 1, 1);// 结果:3System.out.println(s);
static byteArrayToInt() byte数组转int
byte[] bytes = {1,1,0,0};int i = Conversion.byteArrayToInt(bytes, 1, (byte) 1, 1, 1);// 结果:3System.out.println(i);
static byteArrayToLong() byte数组转long
byte[] bytes = {1,1,0,0};long l = Conversion.byteArrayToLong(bytes, 1, (byte) 1, 1, 1);// 结果:3System.out.println(l);
static byteArrayToShort() byte数组转short
byte[] bytes = {1,1,0,0};short s = Conversion.byteArrayToShort(bytes, 1, (byte) 1, 1, 1);// 结果:3System.out.println(s);
static byteArrayToUuid() byte数组转uuid
byte[] bytes = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};// 必须大于15个字节UUID uuid = Conversion.byteArrayToUuid(bytes, 1);// 结果:09080706-0504-0302-1110-0f0e0d0c0b0aSystem.out.println(uuid);
static byteToBinary() byte转bool数组
boolean[] bools = {true,true,false,false};boolean[] booleans = Conversion.byteToBinary((byte) 1, 1, bools, 1, 1);for (boolean bool : booleans) {System.out.println(bool);}/* 结果:truefalsefalsefalse*/
static byteToHex() 字节转字符串
String s = Conversion.byteToHex((byte) 1, 1, "李大爷", 1, 1);// 结果:李0爷System.out.println(s);
static hexDigitMsb0ToBinary() 字符转bool数组
boolean[] booleans = Conversion.hexDigitMsb0ToBinary('d');for (boolean bool : booleans) {System.out.println(bool);}/* 结果:truetruefalsetrue*/
static hexDigitToBinary() 字符转bool数组
boolean[] booleans = Conversion.hexDigitToBinary('d');for (boolean bool : booleans) {System.out.println(bool);}
static hexDigitMsb0ToInt() 字符转整数
int i = Conversion.hexDigitMsb0ToInt('d');// 结果:11System.out.println(i);
static hexDigitToInt() 字符转整数
int i = Conversion.hexDigitToInt('d');// 结果:13System.out.println(i);
static hexToByte() 字符串转byte
byte b = Conversion.hexToByte("ddd", 1, (byte) 1, 1, 1);// 结果:27System.out.println(b);
static hexToInt() 字符串转整数
int i = Conversion.hexToInt("ddd", 1, 1, 1, 1);// 结果:27System.out.println(i);
static hexToLong() 字符串转long
long l = Conversion.hexToLong("ddd", 1, 1, 1, 1);// 结果:27System.out.println(l);
static hexToShort() 字符串转short
short s = Conversion.hexToShort("ddd", 1, (short) 1, 1, 1);// 结果:27System.out.println(s);
static intArrayToLong() int数组转long
int[] ints = {1,1,0,0};long l = Conversion.intArrayToLong(ints, 1, 1, 1, 1);// 结果:3System.out.println(l);
static intToBinary() int转bool数组
boolean[] bools = {true,true,false,false};boolean[] booleans = Conversion.intToBinary(1, 1, bools, 1, 1);for (boolean bool : booleans) {System.out.println(bool);}/* 结果:truefalsefalsefalse*/
static intToByteArray() int转byte数组
byte[] bytes = {1,1,0,0};byte[] bytes1 = Conversion.intToByteArray(1, 1, bytes, 1, 1);for (byte b : bytes1) {System.out.println(b);}/* 结果:1000*/
static intToHex() int转字符串
String s = Conversion.intToHex(1, 1, "李大爷", 1, 1);// 李0爷System.out.println(s);
static intToHexDigit() int转16进制
char c = Conversion.intToHexDigit(12);// 结果:xSystem.out.println(c);
static intToHexDigitMsb0() int转16进制(数字代替)
char c = Conversion.intToHexDigitMsb0(12);// 结果:3System.out.println(c);
static intToShortArray() int转short数组
short[] shorts = {1,1,0,0};short[] shorts1 = Conversion.intToShortArray(1, 1, shorts, 1, 1);for (short s : shorts1) {System.out.println(s);}/* 结果:1000*/
static longToBinary() long转bool数组
boolean[] bools = {true,true,false,false};boolean[] booleans = Conversion.longToBinary(1, 1, bools, 1, 1);for (boolean b : booleans) {System.out.println(b);}/* 结果:truefalsefalsefalse*/
static longToByteArray() long转byte数组
byte[] bytes = {1,1,0,0};byte[] bytes1 = Conversion.longToByteArray(1, 1, bytes, 1, 1);for (byte b : bytes1) {System.out.println(b);}/* 结果:1000*/
static longToHex() long转字符串
String s = Conversion.longToHex(1, 1, "李大爷", 1, 1);// 结果:李0爷System.out.println(s);
static longToIntArray() long转int数组
int[] ints = {1,1,0,0};int[] ints1 = Conversion.longToIntArray(1, 1, ints, 1, 1);for (int i : ints1) {System.out.println(i);}/* 结果:1000*/
static longToShortArray() long转short数组
short[] shorts = {1,1,0,0};short[] shorts1 = Conversion.longToShortArray(1, 1, shorts, 1, 1);for (short s : shorts1) {System.out.println(s);}/* 结果:1000*/
static shortArrayToInt() short数组转int
short[] shorts = {1,1,0,0};int i = Conversion.shortArrayToInt(shorts, 1, 1, 1, 1);// 结果:3System.out.println(i);
static shortArrayToLong() short数组转long
short[] shorts = {1,1,0,0};long l = Conversion.shortArrayToLong(shorts, 1, 1, 1, 1);// 结果:3System.out.println(l);
static shortToBinary() short转boolear
boolean[] bools = {true,true,false,false};boolean[] booleans = Conversion.shortToBinary((short) 1, 1, bools, 1, 1);for (boolean b : booleans) {System.out.println(b);}/* 结果:truefalsefalsefalse*/
static shortToByteArray() short转byte数组
byte[] bytes = {1,1,0,0};byte[] bytes1 = Conversion.shortToByteArray((short) 1, 1, bytes, 1, 1);for (byte b : bytes1) {System.out.println(b);}/* 结果:1000*/
static shortToHex() short转字符串
String s = Conversion.shortToHex((short) 1, 1, "李大爷", 1, 1);// 结果:李0爷System.out.println(s);
static uuidToByteArray uuid转byte数组
byte[] bytes = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};UUID uuid = Conversion.byteArrayToUuid(bytes, 1);byte[] bytes1 = Conversion.uuidToByteArray(uuid, bytes, 1, 1);for (byte b : bytes1) {System.out.println(b);}/* 结果:1234567891011121314151617*/
static allNotNull() 都不为空(多选)
String str = "";Integer num = 0;Double f = 0.0;// 结果:trueSystem.out.println(ObjectUtils.allNotNull(str, num, f));// 结果:falseSystem.out.println(ObjectUtils.allNotNull(str, num, f, null));
static anyNotNull() 至少有一个不为空(多选)
String str = "";Integer num = 0;Double f = 0.0;// 结果:trueSystem.out.println(ObjectUtils.anyNotNull(str, num, f));System.out.println(ObjectUtils.anyNotNull(str, num, f, null));
static clone() 克隆对象
// 克隆字符串String str = "哈哈哈哈";String cloneStr = ObjectUtils.cloneIfPossible(str);// 克隆效果System.out.println("字符串克隆效果:"+cloneStr);cloneStr = "啊啊啊啊";// 克隆mapHashMap<String, String> map = new HashMap<>(1);map.put("name","李大爷");HashMap<String, String> cloneMap = ObjectUtils.cloneIfPossible(map);// 克隆效果System.out.println("map克隆效果:"+cloneMap);cloneMap.put("name","李学霸");// 克隆自定义实例Test test = new Test();test.setName("李大爷");Test cloneTest = ObjectUtils.cloneIfPossible(test);System.out.println("实体类克隆效果:"+cloneTest);cloneTest.setName("李学霸");System.out.println("\r\n最终效果:");System.out.println(str);System.out.println(cloneStr);System.out.println(map);System.out.println(cloneMap);System.out.println(test);System.out.println(cloneTest);/* 输出结果,实体类克隆失败字符串克隆效果:哈哈哈哈map克隆效果:{name=李大爷}实体类克隆效果:Test{name='李大爷'}最终效果:哈哈哈哈啊啊啊啊{name=李大爷}{name=李学霸}Test{name='李学霸'}Test{name='李学霸'}*/
static compare() 比较大小
// 结果:-1System.out.println(ObjectUtils.compare("A", "B"));// 结果:1System.out.println(ObjectUtils.compare('F', 'E'));// 结果:0System.out.println(ObjectUtils.compare(10, 10// 结果:1System.out.println(ObjectUtils.compare(10, null));// 结果:-1System.out.println(ObjectUtils.compare(10, null, true));
static CONST_BYTE() 整数常量转字节
byte b = ObjectUtils.CONST_BYTE(1);
static CONST_SHORT() 整数常量转小整数
short s = ObjectUtils.CONST_SHORT(1);
static CONST() 常量转变量static defaultIfNull() 带默认值取值
String str = "李大爷";// 结果:李大爷System.out.println(ObjectUtils.defaultIfNull(str, "李学霸"));// 结果:李学霸System.out.println(ObjectUtils.defaultIfNull(null, "李学霸"));
static firstNonNull() 取第一个不null的值
Serializable value1 = ObjectUtils.firstNonNull(null, 1, "李大爷");String value2 = ObjectUtils.firstNonNull(null, "", "\r\n", "李大爷");// 结果:1System.out.println(value1);// 结果:""System.out.println(value2);
static identityToString() 取对象原始的 toString 结果
Test test = new Test();StringBuilder sb = new StringBuilder();// 结果存到 StringBuilder 中ObjectUtils.identityToString(sb,test);// 结果:Test{name='null'}System.out.println(test);// 结果:com.lidaye.demo.Test@72ea2f77System.out.println(ObjectUtils.identityToString(test));// 结果:com.lidaye.demo.Test@72ea2f77System.out.println(sb);
static isEmpty() 倒的包里面已经没有了这个方法static max() 取最大值
// 结果:爷System.out.println(ObjectUtils.max("李","大","爷"));// 结果:30System.out.println(ObjectUtils.max(20,null,30));// 结果:aSystem.out.println(ObjectUtils.max('F','a','Z'));
static median() 取中间值
// 结果:李System.out.println(ObjectUtils.median("李","大","爷"));// 不能有null,报错!System.out.println(ObjectUtils.median(20,null,30));// 结果:ZSystem.out.println(ObjectUtils.median('F','a','Z'));// 结果:3System.out.println(ObjectUtils.median(3,1,2,4,6));
static min() 取最小值
// 结果:大System.out.println(ObjectUtils.min("李","大","爷"));// 结果:20System.out.println(ObjectUtils.min(20,null,30));// 结果:FSystem.out.println(ObjectUtils.min('F','a','Z'));
static mode() 重复最多的值
// 结果:李System.out.println(ObjectUtils.mode("李","大","爷","李","学","霸"));// 结果:30System.out.println(ObjectUtils.mode(20,null,30,60,50,30));// 结果:nullSystem.out.println(ObjectUtils.mode('F','a','Z'));
static notEqual() 比较是否不一样
// 结果:falseSystem.out.println(ObjectUtils.notEqual("李","李"));// 结果:trueSystem.out.println(ObjectUtils.notEqual(20,null));
static random() 获取随机字符串
// 随机乱码,结果:𠻶鏦🔹𠀧֣System.out.println(RandomStringUtils.random(8));// 随机英文和数字,结果:MZ0zGCi6System.out.println(RandomStringUtils.random(8,true,true));// 随机数字,结果:68387073System.out.println(RandomStringUtils.random(8,false,true));// 随机英文,结果:pGlamVFZSystem.out.println(RandomStringUtils.random(8,true,false));// 随机乱码另一种实现,结果:𦇣ਣ뇟𣇼꿛System.out.println(RandomStringUtils.random(8,false,false));// 指定范围随机,结果:421A545ASystem.out.println(RandomStringUtils.random(8,0,66,true,true));// 指定随机字符串,结果:大大大大大爷大李System.out.println(RandomStringUtils.random(8,"李大爷"));// 指定随机字符,结果:李李大李大李大大System.out.println(RandomStringUtils.random(8,'李','大','爷'));// 下面两个暂时理解不了System.out.println(RandomStringUtils.random(8,0,66,true,true,'李','大','爷'));System.out.println(RandomStringUtils.random(8,0,66,true,true,new char[]{'李','大','爷'}, new Random()));
static randomAlphabetic() 获取英文随机字符串
// 8位随机,结果:WTMSRAyaSystem.out.println(RandomStringUtils.randomAlphabetic(8));// 8~16位随机,结果:fGfFOHkXeDKaxSystem.out.println(RandomStringUtils.randomAlphabetic(8,16));
static randomAlphanumeric() 获取英文数字随机字符串
// 8位随机,结果:yxufG9xgSystem.out.println(RandomStringUtils.randomAlphanumeric(8));// 8~16位随机,结果:EgzzXIlG5uNSystem.out.println(RandomStringUtils.randomAlphanumeric(8,16));
static randomAscii() 获取ascii字符随机字符串
// 8位随机,结果:ol-5lBjPSystem.out.println(RandomStringUtils.randomAscii(8));// 8~16位随机,结果:elVC$hNlfvn[System.out.println(RandomStringUtils.randomAscii(8,16));
static randomGraph() 获取图字符随机字符串
// 8位随机,结果:2>Wc/zZBSystem.out.println(RandomStringUtils.randomGraph(8));// 8~16位随机,结果:IY|DhGN4OIUJk7{System.out.println(RandomStringUtils.randomGraph(8,16));
static randomNumeric() 获取数字符随机字符串
// 8位随机,结果:63206456System.out.println(RandomStringUtils.randomNumeric(8));// 8~16位随机,结果:50372174320332System.out.println(RandomStringUtils.randomNumeric(8,16));
static randomPrint() 获取打印字符随机字符串
// 8位随机,结果:c`Nl!"ZoSystem.out.println(RandomStringUtils.randomPrint(8));// 8~16位随机,结果:WrQpY*VFn#dQUSystem.out.println(RandomStringUtils.randomPrint(8,16));
static abbreviate() 省略部分字符
// 字符串String str = "12345678910";// 包括省虐号在内5个字符(默认省略号占3个字符),结果:12...System.out.println(StringUtils.abbreviate(str, 5));// 自定义省略符,结果:123@@System.out.println(StringUtils.abbreviate(str,"@@",5));// 前后都省略,结果:...67...System.out.println(StringUtils.abbreviate(str,5,8));// 前后都换成自定义省略符,结果:@456@System.out.println(StringUtils.abbreviate(str,"@",3,5));
static abbreviateMiddle() 省略中间的字符
String str = "12345678910";// 结果:12@10System.out.println(StringUtils.abbreviateMiddle(str,"@",5));
static appendIfMissing() 添加后缀
String str = "12345678910";// 识别是否为5的后缀,不是就添加,结果:123456789105System.out.println(StringUtils.appendIfMissing(str,"5"));// 后缀为5和0的都不添加后缀,结果:12345678910System.out.println(StringUtils.appendIfMissing(str,"5","0"));
static appendIfMissingIgnoreCase() 添加后缀(不分大小写)
String str = "abcdefg";// 结果:abcdefgSystem.out.println(StringUtils.appendIfMissingIgnoreCase(str,"G"));
static capitalize() 首字母大写static uncapitalize() 首字母小写static center() 内容补全
String str = "abcdefg";// 默认空格补全,结果: abcdefgSystem.out.println(StringUtils.center(str,10));// 自定义补全内容,结果:@abcdefg@@System.out.println(StringUtils.center(str,10,'@'));
static chomp() 清除末尾的换行符static chop() 删除最后一个字符static compare() 比较大小
String str1 = "102";String str2 = "11";String str3 = null;// 102 < 11,结果:-1System.out.println(StringUtils.compare(str1,str2));// 11 > null,结果:1System.out.println(StringUtils.compare(str2,str3));// 11 < null,结果:-1System.out.println(StringUtils.compare(str2,str3,false));
static compareIgnoreCase() 比较大小(不分大小写)
String str1 = "ldy";String str2 = "ldY";String str3 = null;// ldy == ldY,结果:0System.out.println(StringUtils.compareIgnoreCase(str1,str2));// ldY > null,结果:1System.out.println(StringUtils.compareIgnoreCase(str2,str3));// ldY < null,结果:-1System.out.println(StringUtils.compareIgnoreCase(str2,str3,false));
static contains() 字符是否包含在字符串内
String str1 = "abcdefghijklmnopq";// 包含字符串,结果:trueSystem.out.println(StringUtils.contains(str1,"lm"));// 包含字符,结果:trueSystem.out.println(StringUtils.contains(str1,'l'));
static containsAny() 字符是否包含在字符串内(多选)
String str1 = "abcdefghijklmnopq";// 包含字符串,结果:trueSystem.out.println(StringUtils. containsAny(str1,"lm","yz"));// 包含字符,结果:trueSystem.out.println(StringUtils. containsAny(str1,'l','z'));
static containsIgnoreCase() 字符是否包含在字符串内(不分大小写)
String str1 = "abcdefghijklmnopq";// 包含字符串,结果:trueSystem.out.println(StringUtils. containsIgnoreCase(str1,"Lm"));
static containsNone() 字符是否包含在字符串内(空参数为真)
String str1 = "abcdefghijklmnopq";String str = null;// 结果:trueSystem.out.println(StringUtils.containsNone(null,"ze"));// 结果:trueSystem.out.println(StringUtils.containsNone(str1,str));
static containsOnly() 字符串的字符仅包含在一个字符集中
String str1 = "acbab";// 包含多个字符,结果:trueSystem.out.println(StringUtils.containsOnly(str1,'a','b','c','d'));// 包含字符串中某个字符,结果:trueSystem.out.println(StringUtils.containsOnly(str1,"abcdefghijklmnopq"));
static containsWhitespace() 字符串中是否包含空白符
// 结果:trueSystem.out.println(StringUtils.containsWhitespace("acb\r\nab"));// 结果:trueSystem.out.println(StringUtils.containsWhitespace("acb ab"));
static countMatches() 字符在字符串中出现的次数
String str = "abafkoipeamfzcvvjasdcmwerfgko";// 结果:2System.out.println(StringUtils.countMatches(str,"ko"));// 结果:3System.out.println(StringUtils.countMatches(str,'f'));
static defaultIfBlank() 字符串默认值(null|""|" ")
String defaultStr = "李大爷";// 结果:abcSystem.out.println(StringUtils.defaultIfBlank("abc",defaultStr));// 结果:李大爷System.out.println(StringUtils.defaultIfBlank("",defaultStr));// 结果:李大爷System.out.println(StringUtils.defaultIfBlank(" ",defaultStr));// 结果:李大爷System.out.println(StringUtils.defaultIfBlank(null,defaultStr));
static defaultIfEmpty() 字符串默认值(null|"")
String defaultStr = "李大爷";// 结果:abcSystem.out.println(StringUtils.defaultIfEmpty("abc",defaultStr));// 结果:李大爷System.out.println(StringUtils.defaultIfEmpty("",defaultStr));// 结果:System.out.println(StringUtils.defaultIfEmpty(" ",defaultStr));// 结果:李大爷System.out.println(StringUtils.defaultIfEmpty(null,defaultStr));
static defaultString() 字符串默认值(null)
// 结果:System.out.println(StringUtils.defaultString(null));// 结果:李大爷System.out.println(StringUtils.defaultString(null,"李大爷"));
static deleteWhitespace() 清除字符串中所有空白
String str = "李 大\r\n爷";// 结果:李大爷System.out.println(StringUtils.deleteWhitespace(str));
static difference() 字符串比较取不同
String str1 = "adwsgergkljasfdnerdsf";String str2 = "adwsgergkwfgsfdnerdsf";// 结果:wfgsfdnerdsfSystem.out.println(StringUtils.difference(str1,str2));
static startsWith() 匹配前缀
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.startsWith(str1,"adw"));
static startsWithAny() 匹配前缀 (多选)
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.startsWithAny(str1,"adw","dsf"));
static startsWithIgnoreCase() 匹配前缀 (部分大小写)
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.startsWithIgnoreCase(str1,"aDW"));
static endsWith() 匹配后缀
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.endsWith(str1,"dsf"));
static endsWithAny() 匹配后缀(多选)
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.endsWithAny(str1,"rtg","dsf"));
static endsWithIgnoreCase() 匹配后缀(不分大小写)
String str1 = "adwsgergkljasfdnerdsf";// 结果:trueSystem.out.println(StringUtils.endsWithIgnoreCase(str1,"Dsf"));
static equals() 字符串比较
String str1 = "abc";String str2 = "ABC";// 结果:falseSystem.out.println(StringUtils.equals(str1,str2));
static equalsIgnoreCase() 字符串比较(不区分大小写)
String str1 = "abc";String str2 = "ABC";// 结果:trueSystem.out.println(StringUtils.equalsIgnoreCase(str1,str2));
static equalsAny() 字符串比较(多选)
String str1 = "abc";String str2 = "acb";String str3 = "abd";String str4 = "abc";// 结果:trueSystem.out.println(StringUtils.equalsAny(str1,str2,str3,str4));
static equalsAnyIgnoreCase() 字符串比较(多选|不区分大小写)
String str1 = "abc";String str2 = "abd";String str3 = "ABC";// 结果:trueSystem.out.println(StringUtils.equalsAnyIgnoreCase(str1,str2,str3));
static firstNonBlank() 区数字第一个有效值(""|" "|null)
String[] strs = {"","\r\n"," ",null,"李大爷"};// 结果:李大爷System.out.println(StringUtils.firstNonBlank(strs));
static firstNonEmpty() 区数字第一个有效值(""|null)
String[] strs1 = {"","李大爷"};String[] strs2 = {"\r\n","李大爷"};String[] strs3 = {" ","李大爷"};String[] strs4 = {null,"李大爷"};// 结果:李大爷System.out.println(StringUtils.firstNonEmpty(strs1));// 结果:\r\nSystem.out.println(StringUtils.firstNonEmpty(strs2));// 结果:System.out.println(StringUtils.firstNonEmpty(strs3));// 结果:李大爷System.out.println(StringUtils.firstNonEmpty(strs4));
static getCommonPrefix() 取字符串数组中公共的前缀‘
String[] strs = {"李大爷","李先生"};// 结果:李System.out.println(StringUtils.getCommonPrefix(strs));
static getDigits() 取出字符串中的数字
String str = "as1l31dwer4f52sdf0";// 结果:1314520System.out.println(StringUtils.getDigits(str));
static getFuzzyDistance() (弃用)static getJaroWinklerDistance() (弃用)static getLevenshteinDistance() (弃用)static indexOf() 取字符在字符串中第一次的位置
String str = "as1l31dwer4f52sdf0";// 结果:6System.out.println(StringUtils.indexOf(str,"dwer"));// 从第4个字符开始,但是字符串是null,结果:-1System.out.println(StringUtils.indexOf(null,'d',3));
static indexOfIgnoreCase() 取字符在字符串中第一次的位置(不分大小写)
String str = "as1l31dwer4f52sdf0";// 结果:6System.out.println(StringUtils.indexOfIgnoreCase(str,"DwEr"));// 从第4个字符开始,但是字符串是null,结果:-1System.out.println(StringUtils.indexOfIgnoreCase(null,"D",3));
static indexOfAny() 字符在字符串中第一次的位置(多选)
String str = "as1l31dwer4f52sdf0";// 匹配出最靠前的结果,结果:4System.out.println(StringUtils.indexOfAny(str,"dwer",null,"31d"));
static indexOfAnyBut() 字符串中第一个不在匹配范围内的字符位置
String str = "as1l31dwer4f52sdf0";// 结果:2System.out.println(StringUtils.indexOfAnyBut(str,"als"));// 结果:2System.out.println(StringUtils.indexOfAnyBut(str,'a','l','s'));
static indexOfDifference() 比较字符串区第一个不同的位置
String str1 = "abcde";String str2 = "abcce";String str3 = "abdde";// 结果:2System.out.println(StringUtils.indexOfDifference(str1,str2,str3));
static isAllBlank() 字符串序列是否都为空(""|" "|null)
String str = " a b c ";// 结果:trueSystem.out.println(StringUtils.isAllBlank(""," ",null,"\r\n"));// 结果:falseSystem.out.println(StringUtils.isAllBlank(""," ",null,"\r\n",str));
static isAllEmpty() 字符串序列是否都为空(""|null)
System.out.println(StringUtils.isAllEmpty("",null));System.out.println(StringUtils.isAllEmpty(""," ",null));
static isAllLowerCase() 是否只包含小写字母
String str = "a bc";// 结果:falseSystem.out.println(StringUtils.isAllLowerCase(str));
static isAllUpperCase() 是否只包含大写字母
String str = "AAB";// 结果:trueSystem.out.println(StringUtils.isAllUpperCase(str));
static isAlpha() 是否只包含Unicode(各国语言不含符号和数字)
String str = "李1";// 结果:falseSystem.out.println(StringUtils.isAlpha(str));
static isAsciiPrintable() 是否只包含ASCII(英文字母|英文符号|数字)
String str1 = "李大爷";// 结果:falseSystem.out.println(StringUtils.isAsciiPrintable(str1));
static isAlphanumeric() 是否只包含(Unicode|数字)
String str = "李1";// 结果:trueSystem.out.println(StringUtils.isAlphanumeric(str));
static isAlphaSpace() 是否只包含(Unicode|' ')
String str = "李 ";System.out.println(StringUtils.isAlphaSpace(str));
static isAlphanumericSpace() 是否只包含(Unicode|数字|' ')
String str = "李 1";// 结果:trueSystem.out.println(StringUtils.isAlphanumericSpace(str));
static isBlank() 是否为(null|""|" ")
String str1 = " ";// 结果:trueSystem.out.println(StringUtils.isBlank(str1));
static isNoneBlank() 是否不为(null|""|" ")
String str1 = " ";// 结果:falseSystem.out.println(StringUtils.isNoneBlank(str1));
static isAnyBlank() 是否包含(null|""|" ")
String str1 = "李 ";String str2 = " ";String str3 = "";String str4 = null;String str5 = "\r\n";// 结果:trueSystem.out.println(StringUtils.isAnyBlank(str1,str2,str3,str4,str5));// 结果:falseSystem.out.println(StringUtils.isAnyBlank(str1));
static isEmpty() 是否为(null|"")
String str1 = " ";// 结果:falseSystem.out.println(StringUtils.isEmpty(str1));
static isNotEmpty() 是否不为(null|"")
String str1 = " ";// 结果:trueSystem.out.println(StringUtils.isNotEmpty(str1));
static isAnyEmpty() 是否包含(null|"")
String str1 = "李 ";String str2 = " ";String str3 = "";String str4 = null;String str5 = "\r\n";// 结果:trueSystem.out.println(StringUtils.isAnyEmpty(str1,str2,str3,str4,str5));// 结果:falseSystem.out.println(StringUtils.isAnyEmpty(str1,str2,str5));
static isMixedCase() 是否包含大小写混合字符
// 结果:trueSystem.out.println(StringUtils.isMixedCase("李大爷lDy"));
static isNumeric() 是否只包含数字
String str = "123456";// 结果:trueSystem.out.println(StringUtils.isNumeric(str));
static isNumericSpace() 是否只包含(数字|" ")
String str = "12 34 56";// 结果:trueSystem.out.println(StringUtils.isNumericSpace(str));
static isWhitespace() 是否只包含(""|" ")
// 结果:tureSystem.out.println(StringUtils.isWhitespace(""));// 结果:tureSystem.out.println(StringUtils.isWhitespace(" "));// 结果:tureSystem.out.println(StringUtils.isWhitespace("\r\n"));// 结果:falseSystem.out.println(StringUtils.isWhitespace(null));
static join() 数组拼接字符串
String[] strs = new String[]{"李大爷","是","个","学","霸"};// 结果:123System.out.println(StringUtils.join('1','2','3'));// 结果:李大爷,是,个,学,霸System.out.println(StringUtils.join(strs,','));// 结果:是~!个~!学~!霸System.out.println(StringUtils.join(Arrays.asList(strs),"~!",1,strs.length));
static joinWith() 数组拼接字符串
String[] strs = new String[]{"李大爷","是","个","学","霸"};// 结果:李大爷~!是~!个~!学~!霸System.out.println(StringUtils.joinWith("~!",strs));
static lastIndexOf() 字符在字符串中最后出现的位置
String str = "李大爷是个大学霸";// 结果:1System.out.println(StringUtils.lastIndexOf(str,"大爷"));// 结果:5System.out.println(StringUtils.lastIndexOf(str,'大'));// 结果:1System.out.println(StringUtils.lastIndexOf(str,'大',3));// 结果:-1System.out.println(StringUtils.lastIndexOf(str,null));
static lastIndexOfAny() 字符在字符串中最后出现的位置(多选)
String str = "李大爷是个大学霸";// 识别位置最大的一个,结果:5System.out.println(StringUtils.lastIndexOfAny(str,"大爷","大",null));
static lastIndexOfIgnoreCase() 字符在字符串中最后出现的位置(不分大小写)
String str = "李大爷A是个大学霸a";// 结果:9System.out.println(StringUtils.lastIndexOfIgnoreCase(str,"A"));// 结果:3System.out.println(StringUtils.lastIndexOfIgnoreCase(str,"A",5));
static lastOrdinalIndexOf() 字符在字符串倒数第几个出现的位置
String str = "李大爷A是个大学霸a";// 第一个A的位置,结果:3System.out.println(StringUtils.lastOrdinalIndexOf(str,"A",1));
static left() 从字符串开头截取多个字符
String str = "李大爷是个大学霸";// 结果:李大爷是个System.out.println(StringUtils.left(str,5));
static leftPad() 字符串开头填充
String str = "李大爷";// 空格填充,结果: 李大爷System.out.println(StringUtils.leftPad(str,5));// 预定义字符填充,结果:@@李大爷System.out.println(StringUtils.leftPad(str,5,'@'));// 预定义字符串填充,结果:12李大爷System.out.println(StringUtils.leftPad(str,5,"123456"));
static right() 从字符串末尾截取多个字符
String str = "abcacb";// 取字符串后四位,结果:cacbSystem.out.println(StringUtils.right(str,4));
static rightPad() 字符串末尾填充
String str = "abcacb";// 超出规定位数右边用*填充,结果:abcacb**System.out.println(StringUtils.rightPad(str,8,'*'));
static length() 获取字符串长度
// 结果:3System.out.println(StringUtils.length("李大爷"));// 结果:0System.out.println(StringUtils.length(null));
static lowerCase() 全部转小写
// 结果:stringSystem.out.println(StringUtils.lowerCase("StRiNg"));// 设置区域不知道有什么用,结果:stringSystem.out.println(StringUtils.lowerCase("StRiNg",Locale.getDefault()));
static upperCase() 全部转大写
// 结果:STRINGSystem.out.println(StringUtils.upperCase("StRiNg"));// 结果:STRINGSystem.out.println(StringUtils.upperCase("StRiNg",Locale.getDefault()));
static mid() 字符串某个位置向后截取多个
// 截取数量超过字符串长度,按字符串长度截取,结果:RiNgSystem.out.println(StringUtils.mid("StRiNg",2,10));
static normalizeSpace()static ordinalIndexOf() 字符在字符串第几个出现的位置
String str = "adewtasfcxcgbwefaf";// 结果:5System.out.println(StringUtils.ordinalIndexOf(str,"a",2));
static overlay() 字符串覆盖字符串的一部分
String str = "adewtasfcxcgbwefaf";String overlay = "李大爷";// 覆盖3-10的内容,结果:ade李大爷cgbwefafSystem.out.println(StringUtils.overlay(str,overlay,3,10));
static prependIfMissing() 添加前缀
String str = "adewtasfcxcgbwefaf";// 结果:0_adewtasfcxcgbwefafSystem.out.println(StringUtils.prependIfMissing(str,"0_"));// 结果:adewtasfcxcgbwefafSystem.out.println(StringUtils.prependIfMissing(str,"0_","we","ad"));
static prependIfMissingIgnoreCase() 添加前缀(不分大小写)
String str = "adewtasfcxcgbwefaf";// 结果:0_adewtasfcxcgbwefafSystem.out.println(StringUtils.prependIfMissingIgnoreCase(str,"0_"));// 结果:adewtasfcxcgbwefafSystem.out.println(StringUtils.prependIfMissingIgnoreCase(str,"0_","we","AD"));
static remove() 删除部分字符
String str = "abcabc";// 结果:bcbcSystem.out.println(StringUtils.remove(str,'a'));// 结果:aaSystem.out.println(StringUtils.remove(str,"bc"));
static removeIgnoreCase() 删除部分字符(不分大小写)
String str = "abcabc";// 结果:acacSystem.out.println(StringUtils.removeIgnoreCase(str,"B"));
static removeEnd() 删除后缀
String str = "adewtasfcxcgbwefaf";// 结果:adewtasfcxcgbweSystem.out.println(StringUtils.removeEnd(str,"faf"));
static removeEndIgnoreCase() 删除后缀(不分大小写)
String str = "adewtasfcxcgbwefaf";// 结果:adewtasfcxcgbweSystem.out.println(StringUtils.removeIgnoreCase(str,"FAF"));
static removeStart() 删除前缀
String str = "adewtasfcxcgbwefaf";// 结果:tasfcxcgbwefafSystem.out.println(StringUtils.removeStart(str,"adew"));
static removeStartIgnoreCase() 删除前缀(不分大小写)
String str = "adewtasfcxcgbwefaf";// 结果:wtasfcxcgbwefafSystem.out.println(StringUtils.removeStartIgnoreCase(str,"ADE"));
static repeat() 字符串重复
String str = "李大爷";// 重复两次,结果:李大爷李大爷System.out.println(StringUtils.repeat(str,2));// 复制三次,&分隔,结果:李大爷&李大爷&李大爷System.out.println(StringUtils.repeat(str,"&",3));
static replace() 字符串替换
String str = "abcacb";// 把a全部替换成e,结果:ebcecbSystem.out.println(StringUtils.replace(str, "a", "e"));// 把a全部替换成e最多替换1个,结果:ebcacbSystem.out.println(StringUtils.replace(str, "a", "e",1));
static replaceIgnoreCase() 字符串替换(不分大小写)
String str = "abcacb";// 把a或A替换成g,结果:gbcgcbSystem.out.println(StringUtils.replaceIgnoreCase(str, "A", "g"));// 把a或A替换成g,只替换1个,结果:gbcacbSystem.out.println(StringUtils.replaceIgnoreCase(str, "A", "g",1));
static replaceOnce() 字符串替换(只替换一个)
String str = "abcacb";// 把第一个a替换成g,结果:gbcacbSystem.out.println(StringUtils.replaceOnce(str, "a", "g"));
static replaceOnceIgnoreCase() 字符串替换(只替换一个不分大小写)
String str = "abcacb";// 把第一个a或A替换成g,结果:gbcacbSystem.out.println(StringUtils.replaceOnceIgnoreCase(str, "A", "g"));
static replaceChars() 字符串替换(支持char类型参数)
String str = "abcacb";// 把a全部替换成e,结果:ebcecbSystem.out.println(StringUtils.replaceChars(str, "a", "e"));// 把b全部替换成f,结果:afcacfSystem.out.println(StringUtils.replaceChars(str, 'b','f'));
static replaceEach() 批量字符串替换
String str = "abcacb";// 把a,b全部替换成e,f,结果:efcecfSystem.out.println(StringUtils.replaceEach(str, new String[]{"a","b"}, new String[]{"e","f"}));
static replaceEachRepeatedly() 批量字符串反复替换
String str = "abcacb";// 把a替换成e,再把e替换成f,结果:fbcfcbSystem.out.println(StringUtils.replaceEachRepeatedly(str, new String[]{"e","a"}, new String[]{"f","e"}));
static reverse() 字符串反转
// 结果:爷大李System.out.println(StringUtils.reverse("李大爷"));
static reverseDelimited() 根据指定字符反转字符串
// 结果:大爷,李System.out.println(StringUtils.reverseDelimited("李,大爷",','));
static rotate() 字符串位移
String str = "abcacb";// 向右位移两位,结果:cbabcaSystem.out.println(StringUtils.rotate(str,2));
static split() 字符串拆分成数组
String str = "ab,,ca c,b";// 默认以空格拆分,结果:{"ab,,ca","c,b"}System.out.println(Arrays.asList(StringUtils.split(str)));// 以逗号拆分,结果:{"ab","ca c","b"}System.out.println(Arrays.asList(StringUtils.split(str,',')));// 以逗号拆分,最多拆分两份,结果:{"ab","ca c,b"}System.out.println(Arrays.asList(StringUtils.split(str,",",2)));
static splitPreserveAllTokens() 字符串拆分成数组(识别相邻分隔符)
String str = "ab,,ca c,b";// 默认以空格拆分,结果:{"ab,,ca","c,b"}System.out.println(Arrays.asList(StringUtils.splitPreserveAllTokens(str)));// 以逗号拆分,结果:{"ab","","ca c","b"}System.out.println(Arrays.asList(StringUtils.splitPreserveAllTokens(str,',')));// 以逗号拆分,最多拆分两份,结果:{"ab",",ca c,b"}System.out.println(Arrays.asList(StringUtils.splitPreserveAllTokens(str,",",2)));
static splitByCharacterType() 字符根据字符类型串拆分成数组
String str = "aB,李大爷ca c,b";// 结果:{"a","B",",","李大爷","ca"," ","c",",","b"}System.out.println(Arrays.asList(StringUtils.splitByCharacterType(str)));
static splitByCharacterTypeCamelCase() 字符串根据类型和驼峰拆分成数组
String str = "HellowWorld";// 结果:{"Hellow","World"}System.out.println(Arrays.asList(StringUtils.splitByCharacterTypeCamelCase(str)));
static splitByWholeSeparator() 字符串根据指定字符串拆分
// 存在分隔符相邻的情况String str = "ab,,ca c,b";// 以","拆分,结果:{"ab","ca c","b"}System.out.println(Arrays.asList(StringUtils.splitByWholeSeparator(str,",")));// 以","拆分,最多拆分两份,结果:{"ab","ca c,b"}System.out.println(Arrays.asList(StringUtils.splitByWholeSeparator(str,",",2))
statuc splitByWholeSeparatorPreserveAllTokens() 字符串根据指定字符串拆分(识别相邻分隔符)
// 存在分隔符相邻的情况String str = "ab,,ca c,b";// 以","拆分,结果:{"ab","","ca c","b"}System.out.println(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(str,",")));// 以","拆分,最多拆分两份,结果:{"ab",",ca c,b"}System.out.println(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(str,",",2)));
static strip() 去除头尾空白符
tring str = "\r\n 李大爷 ";// 去除空白符,结果:李大爷System.out.println(StringUtils.strip(str));// 去除"大爷 ",结果:\r\n 李System.out.println(StringUtils.strip(str,"大爷 "));
static stripToEmpty() 去除头尾空白符(只去除空白符)
// 结果:""System.out.println(StringUtils.stripToEmpty(null));// 结果:李大爷System.out.println(StringUtils.stripToEmpty("\r\n 李大爷 "));
static stripToNull() 去除头尾空白符(只去除空白符)
// 结果:nullSystem.out.println(StringUtils.stripToNull(""));// 结果:李大爷System.out.println(StringUtils.stripToNull("\r\n 李大爷 "));
static stripAll() 去除头尾空白符(多个)
String[] strs = {"李\r\n", "大 ", "\r\n爷"};// 清楚数组中所有字符串首尾的空白符,结果:{"李","大","爷"}System.out.println(Arrays.asList(StringUtils.stripAll(strs)));// 清楚多个字符串首位的空白符,结果:{"李","大","爷"}System.out.println(Arrays.asList(StringUtils.stripAll("李\r\n", "大 ", "\r\n爷")));
static stripEnd() 去除指定后缀
// 结果:李System.out.println(StringUtils.stripEnd("李大爷","大爷"));
static stripStart() 去除指定前缀
// 结果:大爷System.out.println(StringUtils.stripStart("李大爷","李"));
static stripAccents() 去除字符串中的变音符号
String str = "áü";// 结果:auSystem.out.println(StringUtils.stripAccents(str));
static substring() 字符串截取
String str = "李大爷";// 结果:爷System.out.println(StringUtils.substring(str,2));// 结果:爷System.out.println(StringUtils.substring(str,2,5));// 结果:nullSystem.out.println(StringUtils.substring(null,2,5));
static substringAfter() 截取指定字符串后的字符
String str = "李大爷";// 结果:爷System.out.println(StringUtils.substringAfter(str,"大"));// 结果:""System.out.println(StringUtils.substringAfter(str,"牛逼"));
static substringAfterLast() 截取指定字符串最后出现位置后的字符
// 结果:牛逼System.out.println(StringUtils.substringAfterLast("李大爷李牛逼","李"));
static substringBefore() 截取指定字符串钱的字符
String str = "李大爷";// 结果:李System.out.println(StringUtils.substringBefore(str,"大"));// 结果:""System.out.println(StringUtils.substringBefore(str,"牛逼"));
static substringBeforeLast() 截取指定字符串最后出现位置后的字符
// 结果:李大爷System.out.println(StringUtils.substringBeforeLast("李大爷李牛逼","李"));
static substringBetween() 截取两个指定字符串之间的字符
String str = "李大爷李牛逼";// 结果:大爷System.out.println(StringUtils.substringBetween(str,"李"));// 结果:大爷李System.out.println(StringUtils.substringBetween(str,"李","牛逼"));
static substringsBetween() 截取两个指定字符串之间的字符(多个结果)
String str = "李大爷李小爷";// 结果:{"大","小"}System.out.println(Arrays.asList(StringUtils.substringsBetween(str,"李","爷")));
static swapCase() 切换大小写
// 结果:lIDAYESystem.out.println(StringUtils.swapCase("Lidaye"));
static toCodePoints() 字符串转代码点
int[] lidayes = StringUtils.toCodePoints("Lidaye");// 结果:76,105,100,97,121,101,for (int lidaye : lidayes) {System.out.println(lidaye);}
static toEncodedString() 字节转字符串
String str = "李大爷";// 转字节byte[] bytes = str.getBytes();// 转字符,结果:李大爷System.out.println(StringUtils.toEncodedString(bytes, Charset.defaultCharset()));
static trim() 去除首位控制字符(char <= 32)
String str = " 李大爷 \r\n";// 结果:李大爷System.out.println(StringUtils.trim(str));// 结果:nullSystem.out.println(StringUtils.trim(null));
static trimToEmpty() 去除首位控制字符(char <= 32)
// 结果:李大爷System.out.println(StringUtils.trimToEmpty(" 李大爷 \r\n"));// 结果:""System.out.println(StringUtils.trimToEmpty(null));
static trimToNull() 去除首位控制字符(char <= 32)
// 结果:李大爷System.out.println(StringUtils.trimToNull(" 李大爷 \r\n"));// 结果:nullSystem.out.println(StringUtils.trimToNull(" "));
static truncate() 裁减字符串
String str = "李大爷";// 最多保留两位长度,结果:李大System.out.println(StringUtils.truncate(str,2));// 最多保留两位长度,第二个字符开始,结果:大爷System.out.println(StringUtils.truncate(str,1,2));
static unwrap() 清除指定一致的前后缀
// 结果:大爷System.out.println(StringUtils.unwrap("李大爷李","李"));
static wrap() 添加同样的前后缀
String str = "大爷";// 结果:李大爷李System.out.println(StringUtils.wrap(str,'李'));// 结果:李大爷李System.out.println(StringUtils.wrap(str,"李"));
static wrapIfMissing() 添加同样的前后缀(不重复添加)
String str = "李大爷";// 结果:李大爷李System.out.println(StringUtils.wrapIfMissing(str,'李'));// 结果:李大爷李System.out.println(StringUtils.wrapIfMissing(str,"李"));
static getEnvironmentVariable() 取环境变量并设置备用值
// 结果:D:\tool\java\jdk\jdk1.8System.out.println(SystemUtils.getEnvironmentVariable("JAVA_HOME", "李大爷"));// 结果:李大爷System.out.println(SystemUtils.getEnvironmentVariable("LIDAYE_HOME", "李大爷"));
static getHostName() 获取主机名
// 结果:SD-20191104SIHESystem.out.println(SystemUtils.getHostName());
static getJavaHome() 获取 JAVA_HOME
// 结果:D:\tool\java\jdk\jdk1.8System.out.println(SystemUtils.getJavaHome());
static getJavaIoTmpDir() 获取 java IO 的临时文件目录
// 结果:C:\Users\ADMINI~1\AppData\Local\TempSystem.out.println(SystemUtils.getJavaIoTmpDir());
static getUserDir() 获取当前项目所在目录
// 结果:D:\tool\project\demo2System.out.println(SystemUtils.getUserDir());
static getUserHome() 获取用户主目录
// 结果:C:\Users\AdministratorSystem.out.println(SystemUtils.getUserHome());
static isJavaAwtHeadless() 是否开启Headless
// falseSystem.out.println(SystemUtils.isJavaAwtHeadless());
static isJavaVersionAtLeast() java 版本
// 以下结果都为:trueSystem.out.println(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8));System.out.println(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_7));System.out.println(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_6));System.out.println(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
static isJavaVersionAtMost() 包中没有该方法static exclusiveBetween() 校验参数的取值范围
// 模拟传入参数long time = System.currentTimeMillis();double price = 0.5;String str = "D";Validate.exclusiveBetween("A","Z",str);Validate.exclusiveBetween(0,1,price);// 报错!// The value 1583140578428 is not in the specified exclusive range of 1583140578423 to 1583140578426Validate.exclusiveBetween(time-5,time-2,time);
static inclusiveBetween() 校验参数的取值范围exclusiveBetween() 一样static finite() 过滤无限和NAN
double price1 = 1.0 / 0.0;double price2 = price1 * 0.0;// 结果:InfinitySystem.out.println(price1);// 结果:NaNSystem.out.println(price2);// 报错!// price1=Infinity 异常提示Validate.finite(price1,"price1=%s 异常提示",price1);
static isAssignableFrom() 两个类是否相同或所属
Integer num = 0;List list = new ArrayList();// 父类/父接口在前,子类在后Validate.isAssignableFrom(Comparable.class,num.getClass());// 报错!Validate.isAssignableFrom(Map.class,list.getClass());
static isInstanceOf() 对象是否为类的实例
Integer num = 0;List list = new ArrayList();Validate.isInstanceOf(Comparable.class,num);Validate.isInstanceOf(Map.class,list);
static isTrue() 条件是否为真
Validate.isTrue(true);// 报错!抛出异常啦啦啦啦~Validate.isTrue(false,"抛出异常%s","啦啦啦啦);// 报错!抛出异常1Validate.isTrue(false,"抛出异常%s",1);// 报错!抛出异常1.0Validate.isTrue(false,"抛出异常%s",1.0);
static matchesPattern() 正则校验字符串
String num = "1234567";Validate.matchesPattern(num,"\\d{7}$","%s不是7位数字",num);
static noNullElements() 校验数组中是否有空值
String[] param1 = {"李","大","爷"};// 测试map数组的空判断是否生效Map<String, String> param2 = new HashMap<>(3);param2.put("li","李");param2.put("da",null);param2.put("ye","爷");// 都没有报错Validate.noNullElements(param1);Validate.noNullElements(Arrays.asList(param1));Validate.noNullElements(ArrayUtils.toArray(param2));
static notBlank() 字符串序非空校验(\r\m | " ")
StringBuilder param1 = new StringBuilder("李大爷");StringBuffer param2 = new StringBuffer("\r\n");StringBuffer param3 = new StringBuffer(" ");Validate.notBlank(param1);// 报错!param2=\r\n抛出异常Validate.notBlank(param2,"param2=%s 抛出异常",param2);// 报错!param3= 抛出异常Validate.notBlank(param3,"param3=%s 抛出异常",param3);
static notEmpty() 字符串序非空校验
StringBuilder[] param1 = {new StringBuilder("李大爷"),new StringBuilder("李学霸")};StringBuffer param2 = new StringBuffer("\r\n");StringBuffer param3 = new StringBuffer(" ");StringBuffer param4 = new StringBuffer();Validate.notEmpty(param1);Validate.notEmpty(param2);Validate.notEmpty(param3);// 报错!param4= 抛出异常Validate.notEmpty(param4,"param4=%s 抛出异常",param4);
static notNaN() 非NaN过滤
double nan = 1.0/0.0*0.0;// 报错!param1=NaN 抛出异常Validate.notNaN(nan,"param1=%s 抛出异常",nan);
static notNull() 非null过滤
// 报错!报错啦啦啦啦啦啦Validate.notNull(null,"报错%s","啦啦啦啦啦啦");
static validIndex() 数组下标有效性校验
String[] strs = {"李",null,"爷"};List<String> list = new ArrayList<>();list.add("1");list.add("2");Validate.validIndex(strs,1);// 报错!数组中没有该下标哦哦哦哦哦~Validate.validIndex(list,2,"数组中没有该下标%s","哦哦哦哦哦~");
static validState() 真假校验isTrue() 的弱化版
Validate.validState(false,"报错啦~~%s","啊啊啊啊~");
time 日期时间工具类
常用格式:
yyyy-MM-dd HH:mm:ss
format() 格式化时间
String pattern = "yyyy-MM-dd hh:mm:ss";// 以下结果都是:2020-03-06 02:53:37System.out.println(DateFormatUtils.format(Calendar.getInstance(), pattern));System.out.println(DateFormatUtils.format(new Date(), pattern));System.out.println(DateFormatUtils.format(System.currentTimeMillis(), pattern));System.out.println(DateFormatUtils.format(System.currentTimeMillis(), pattern, TimeZone.getDefault()));System.out.println(DateFormatUtils.format(System.currentTimeMillis(), pattern, Locale.getDefault()));System.out.println(DateFormatUtils.format(System.currentTimeMillis(), pattern, TimeZone.getDefault(),Locale.getDefault()));
formatUTC() UTC时区格式化时间
String pattern = "yyyy-MM-dd hh:mm:ss";// 以下结果都是:2020-03-06 06:56:40System.out.println(DateFormatUtils.formatUTC(new Date(), pattern));System.out.println(DateFormatUtils.formatUTC(System.currentTimeMillis(), pattern));System.out.println(DateFormatUtils.formatUTC(System.currentTimeMillis(), pattern,Locale.getDefault()));
static addMilliseconds() 数毫秒后
// 获取 dataObj 对象向后推1000毫秒后的对象Date date = DateUtils.addMilliseconds(new Date(), 1000);
static addSeconds() 数秒后
// 获取 dataObj 对象向后推10秒后的对象Date date = DateUtils.addSeconds(new Date(), 10);
static addMinutes() 数分钟后
// 获取 dataObj 对象向后推5分钟后的对象Date date = DateUtils.addMinutes(new Date(), 5);
static addHours() 数小时后
// 获取 dataObj 对象向后推3小时后的对象Date date = DateUtils.addHours(new Date(), 3);
static addDays() 数天后
// 获取 dataObj 对象向后推3天后的对象Date date = DateUtils.addDays(new Date(), 3);
static addWeeks() 数周后
// 获取 dataObj 对象向后推3周后的对象Date date = DateUtils.addWeeks(new Date(), 3);
static addMonths() 数月后
// 获取 dataObj 对象向后推3个月后的对象Date date = DateUtils.addMonths(new Date(), 3);
static addYears() 数年后
// 获取 dataObj 对象向后推1年后的对象Date date = DateUtils.addYears(dateObj, 1);
static ceiling() 获取日期上限
/*** 假设当前时间 2019-10-21 10:03:00* Calendar.AM(0): 0001-01-01 00:00:00* Calendar.YEAR(1): 2020-01-01 00:00:00* Calendar.MONTH(2): 2019-11-01 00:00:00* Calendar.DATE(5): 2019-10-22 00:00:00* Calendar.AM_PM(9): 2019-10-21 12:00:00* Calendar.HOUR(10): 2019-10-21 11:00:00* Calendar.DECEMBER(11): 2019-10-21 11:00:00* Calendar.MINUTE(12): 2019-10-21 10:04:00* Calendar.SECOND(13): 2019-10-21 10:03:01* Calendar.MILLISECOND(14): 2019-10-21 10:03:00*/Date ceiling = DateUtils.ceiling(new Date(), Calendar.HOUR);
static getFragmentInMilliseconds() 相对的第几毫秒
/*** 假设当前时间 2019-10-21 10:49:16* Calendar.YEAR(1): 25354156808* Calendar.MONTH(2): 1766956809* Calendar.DATE(5): 38956809* Calendar.FRIDAY(6): 38956809* Calendar.DECEMBER(11): 2956809* Calendar.MINUTE(12): 16809* Calendar.SECOND(13): 809*/long millisecond = DateUtils.getFragmentInMilliseconds(new Date(), Calendar.YEAR);
static getFragmentInSeconds() 相对的第几秒
/*** 假设当前时间 2019-10-21 11:00:29* Calendar.YEAR(1): 25354830* Calendar.MONTH(2): 1767630* Calendar.DATE(5): 39630* Calendar.FRIDAY(6): 39630* Calendar.DECEMBER(11): 30* Calendar.MINUTE(12): 30*/long second = DateUtils.getFragmentInSeconds(new Date(), Calendar.YEAR);
static getFragmentInMinutes() 相对的第几分钟
/*** 假设当前时间 2019-10-21 10:57:20* Calendar.YEAR(1): 422577* Calendar.MONTH(2): 29457* Calendar.DATE(5): 657* Calendar.FRIDAY(6): 657* Calendar.DECEMBER(11): 57*/long minute = DateUtils.getFragmentInMinutes(new Date(), Calendar.YEAR);
static getFragmentInHours() 相对的第几个小时
/*** 假设当前时间 2019-10-21 10:43:13* Calendar.YEAR(1): 7042* Calendar.MONTH(2): 490* Calendar.DATE(5): 10* Calendar.FRIDAY(6): 10*/long hour = DateUtils.getFragmentInHours(new Date(), Calendar.YEAR);
static getFragmentInDays() 相对的第几天
/*** 假设当前时间 2019-10-21 10:03:00* Calendar.YEAR(1): 294* Calendar.MONTH(2): 21*/long day = DateUtils.getFragmentInDays(new Date(), Calendar.MONTH);
static isSameDay() 是否同一天
boolean sameDay = DateUtils.isSameDay(new Date(), new Date());
static isSameInstant() 是否同一毫秒
boolean sameInstant = DateUtils.isSameInstant(new Date(), new Date());
static isSameLocalTime() 是否同一个本地时间
boolean sameInstant = DateUtils.isSameLocalTime(DateUtils.toCalendar(new Date()),DateUtils.toCalendar(new Date()));
static iterator() 获取时间范围迭代器
/*** DateUtils.RANGE_WEEK_SUNDAY(1): 从上周日开始的一周* DateUtils.RANGE_WEEK_MONDAY(2): 从本周一开始的一周* DateUtils.RANGE_WEEK_RELATIVE(3): 从今天开始的一周* DateUtils.RANGE_WEEK_CENTER(4): 以今天为中心的一周* DateUtils.RANGE_MONTH_SUNDAY(5): 从上月最后一个周日开始的一个月* DateUtils.RANGE_MONTH_MONDAY(6): 从上月最后一个周一开始的一个月*/Iterator<Calendar> iterator = DateUtils.iterator(DateUtils.addDays(new Date(),1), DateUtils.RANGE_MONTH_MONDAY);while (iterator.hasNext()){Calendar next = iterator.next();}
static parseDate() 字符串转 Date
Date date = DateUtils.parseDate("2019-10-21 11:59:04", "yyyy-MM-dd hh:mm:ss");
static parseDateStrictly() 字符串转 Date (严格的)
Date date = DateUtils.parseDateStrictly("2019-10-21 11:59:04", "yyyy-MM-dd hh:mm:ss");
static round() 日期四舍五入
/*** 假设当前时间 2019-10-21 03:07:36* Calendar.YEAR(1): 2020-01-01 00:00:00* Calendar.MONTH(2): 2019-11-01 00:00:00* Calendar.DATE(5): 2019-10-22 00:00:00* Calendar.AM_PM(9): 2019-10-21 12:00:00* Calendar.HOUR(10): 2019-10-21 03:00:00* Calendar.DECEMBER(11): 2019-10-21 03:00:00* Calendar.MINUTE(12): 2019-10-21 03:08:00* Calendar.SECOND(13): 2019-10-21 03:07:37* Calendar.MILLISECOND(14): 2019-10-21 03:07:36*/Date date = DateUtils.round(new Date(), Calendar.YEAR);
static setMilliseconds() 修改毫秒的值
// 修改成100毫秒Date date = DateUtils.setMilliseconds(new Date(), 100);
static setSeconds() 修改秒的值
// 修改成45秒Date date = DateUtils.setSeconds(new Date(), 45);
static setMinutes() 修改分的值
// 修改成30分Date date = DateUtils.setMinutes(new Date(), 30);
static setHours() 修改小时的值
// 修改成晚上八点Date date = DateUtils.setHours(new Date(), 20);
static setDays() 修改天的值
// 修改成21日Date date = DateUtils.setDays(new Date(), 21);
static setMonths() 修改月份的值
// 修改成5月份Date date = DateUtils.setMonths(new Date(), 5);
static setYears() 修改年份的值
// 修改成2020年Date date = DateUtils.setYears(new Date(), 2020);
static toCalendar() 创建日历对象
Calendar calendar = DateUtils.toCalendar(new Date());
static truncate() 时间向下取整
/*** 假设当前时间 2019-10-21 06:45:18* Calendar.YEAR(1): 2019-01-01 00:00:00* Calendar.MONTH(2): 2019-10-01 00:00:00* Calendar.DATE(5): 2019-10-21 00:00:00* Calendar.AM_PM(9): 2019-10-21 12:00:00* Calendar.HOUR(10): 2019-10-21 18:00:00* Calendar.DECEMBER(11): 2019-10-21 18:00:00* Calendar.MINUTE(12): 2019-10-21 18:45:00* Calendar.SECOND(13): 2019-10-21 18:45:18* Calendar.MILLISECOND(14): 2019-10-21 18:45:18*/Date date = DateUtils.truncate(new Date(), Calendar.YEAR);
static truncatedCompareTo() 位置值比较
/*** Calendar.YEAR(1): 0* Calendar.MONTH(2): 0* Calendar.DATE(5): 0* Calendar.AM_PM(9): 0* Calendar.HOUR(10): 1* Calendar.DECEMBER(11): 1* Calendar.MINUTE(12): 1* Calendar.SECOND(13): 1* Calendar.MILLISECOND(14): 1*/int num = DateUtils.truncatedCompareTo(DateUtils.addHours(new Date(), 1),new Date(),Calendar.YEAR);
static truncatedEquals() 位置值比较
/*** Calendar.YEAR(1): true* Calendar.MONTH(2): true* Calendar.DATE(5): true* Calendar.AM_PM(9): true* Calendar.HOUR(10): false* Calendar.DECEMBER(11): false* Calendar.MINUTE(12): false* Calendar.SECOND(13): false* Calendar.MILLISECOND(14): false*/boolean res = DateUtils.truncatedEquals(DateUtils.addHours(new Date(), 1),new Date(),Calendar.YEAR);
| 占位符 | 寓意 |
|---|---|
| y | 年 |
| M | 月 |
| d | 天 |
| H | 小时 |
| m | 分钟 |
| s | 秒 |
| S | 毫秒 |
static formatDuration() 毫秒换算成相应的格式
// 毫秒long timeGap = 3600000L;// 换算成小时String dayFormatPattern = "结果:HHH小时";// 默认位数不足补0,结果:001小时System.out.println(DurationFormatUtils.formatDuration(timeGap,dayFormatPattern));// 参数3设为false不补0,结果:1小时System.out.println(DurationFormatUtils.formatDuration(timeGap,dayFormatPattern,false));
static formatDurationHMS() 毫秒格式化为时分秒毫秒
// 毫秒long timeGap = 3600000L;// 同等于 formatDuration 的 HH:mm:ss.SSS 格式System.out.println(DurationFormatUtils.formatDurationHMS(timeGap));// 结果:01:00:00.000
static formatDurationISO() 毫秒格式化为ISO8601格式
// 毫秒long timeGap = 3600000L;// 同等于 formatDuration 的 'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S' 格式System.out.println(DurationFormatUtils.formatDurationISO(timeGap));// 结果:P0Y0M0DT1H0M0.000S
static formatDurationWords() 毫秒格式化带英文说明
// 毫秒long timeGap = 3600000L;// 只显示不为0的,结果:1 hourSystem.out.println(DurationFormatUtils.formatDurationWords(timeGap,true,true));// 向前补0,结果:0 days 1 hourSystem.out.println(DurationFormatUtils.formatDurationWords(timeGap,false,true));// 向后补0,结果:1 hour 0 minutes 0 secondsSystem.out.println(DurationFormatUtils.formatDurationWords(timeGap,true,false));// 前后都补0,结果:0 days 1 hour 0 minutes 0 secondsSystem.out.println(DurationFormatUtils.formatDurationWords(timeGap,false,false));
static formatPeriod() 两个时间之间间隔的毫秒换算成相应的格式
// 时间1long timeGap = System.currentTimeMillis();// 时间2long timeGap2 = timeGap+3600000;// 换算格式String dayFormatPattern = "结果:HHH小时";// 默认补0,结果:001小时System.out.println(DurationFormatUtils.formatPeriod(timeGap,timeGap2,dayFormatPattern));// 不补0,最后的参数为时区,结果:1小时System.out.println(DurationFormatUtils.formatPeriod(timeGap,timeGap2,dayFormatPattern,false, TimeZone.getDefault()));
static formatPeriodISO() 两个时间之间间隔的毫秒格式化为ISO8601格式
// 时间1long timeGap = System.currentTimeMillis();// 时间2long timeGap2 = timeGap+3600000;// 同等于 formatPeriod 的 'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S' 格式System.out.println(DurationFormatUtils.formatPeriodISO(timeGap,timeGap2));// 结果:P0Y0M0DT1H0M0.000S
static getInstance() 获取指定格式规则的格式化对象
// 当前时间戳long time = System.currentTimeMillis();// 格式化对象FastDateFormat fastDateFormat1 = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");// 指定区域FastDateFormat fastDateFormat2 = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss",Locale.CHINA);// 指定时区FastDateFormat fastDateFormat3 = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss",TimeZone.getDefault());// 指定区域和时区FastDateFormat fastDateFormat4 = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss",TimeZone.getDefault(),Locale.CHINA);// 结果都是一样的:2020-01-08 10:22:56System.out.println(fastDateFormat1.format(new Date(time)));System.out.println(fastDateFormat2.format(new Date(time)));System.out.println(fastDateFormat3.format(new Date(time)));System.out.println(fastDateFormat4.format(new Date(time)));
static getDateInstance() 获取预定义格式化对象(年月日周)
// 当前时间戳long time = System.currentTimeMillis();// FastDateFormat.SHORT:简日期格式(20-1-8)// FastDateFormat.MEDIUM:常规日期格式(2020-1-8)// FastDateFormat.LONG:当前区域的日期格式(2020年1月8日)// FastDateFormat.FULL:当前区域的完整格式(2020年1月8日 星期三)FastDateFormat fastDateFormat1 = FastDateFormat.getDateInstance(FastDateFormat.LONG);// 设置区域FastDateFormat fastDateFormat1 = FastDateFormat.getDateInstance(FastDateFormat.LONG,Locale.ENGLISH);// 设置时区FastDateFormat fastDateFormat2 = FastDateFormat.getDateInstance(FastDateFormat.LONG,TimeZone.getDefault());// 设置时区和区域FastDateFormat fastDateFormat3 = FastDateFormat.getDateInstance(FastDateFormat.LONG,TimeZone.getDefault(),Locale.CHINA);// 结果:2020年1月8日System.out.println(fastDateFormat1.format(new Date(time)));// 结果:January 8, 2020System.out.println(fastDateFormat2.format(new Date(time)));// 结果:2020年1月8日System.out.println(fastDateFormat3.format(new Date(time)));// 结果:2020年1月8日System.out.println(fastDateFormat4.format(new Date(time)));
static getTimeInstance() 获取预定义格式化对象(时分秒)
// 当前时间戳long time = System.currentTimeMillis();// FastDateFormat.SHORT:简时间格式(上午11:07)// FastDateFormat.MEDIUM:常规格式(11:07:11)// FastDateFormat.LONG:当前区域的时间格式(上午11时07分11秒)// FastDateFormat.FULL:当前区域的完整格式(上午11时07分11秒 CST)FastDateFormat fastDateFormat1 = FastDateFormat.getTimeInstance(FastDateFormat.LONG);// 设置区域FastDateFormat fastDateFormat2 = FastDateFormat.getTimeInstance(FastDateFormat.LONG,Locale.ENGLISH);// 设置时区FastDateFormat fastDateFormat3 = FastDateFormat.getTimeInstance(FastDateFormat.LONG,TimeZone.getDefault());// 设置地区和时区FastDateFormat fastDateFormat4 = FastDateFormat.getTimeInstance(FastDateFormat.LONG,TimeZone.getDefault(),Locale.CHINA);// 结果:上午11时16分35秒System.out.println(fastDateFormat1.format(new Date(time)));// 结果:11:16:35 AM CSTSystem.out.println(fastDateFormat2.format(new Date(time)));// 结果:上午11时16分35秒System.out.println(fastDateFormat3.format(new Date(time)));// 结果:上午11时16分35秒System.out.println(fastDateFormat4.format(new Date(time)));
static getDateTimeInstance() 获取预定义格式化对象(年月日 时分秒)getDateInstance() 和 getTimeInstance() 的整合格式
// 当前时间戳long time = System.currentTimeMillis();// 参数使用说明参考 getDateInstance 和 getTimeInstanceFastDateFormat fastDateFormat1 = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG,FastDateFormat.LONG);FastDateFormat fastDateFormat2 = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG,FastDateFormat.LONG,Locale.ENGLISH);FastDateFormat fastDateFormat3 = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG,FastDateFormat.LONG,TimeZone.getDefault());FastDateFormat fastDateFormat4 = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG,FastDateFormat.LONG,TimeZone.getDefault(),Locale.CHINA);// 结果:2020年1月8日 上午11时25分25秒System.out.println(fastDateFormat1.format(new Date(time)));// 结果:January 8, 2020 11:25:25 AM CSTSystem.out.println(fastDateFormat2.format(new Date(time)));// 结果:2020年1月8日 上午11时25分25秒System.out.println(fastDateFormat3.format(new Date(time)));// 结果:2020年1月8日 上午11时25分25秒System.out.println(fastDateFormat4.format(new Date(time)));
parse() 字符串转换成日期对象
FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd");// 按照格式识别成日期对象Date date1 = fastDateFormat.parse("2020-01-08");// 从第四个字符开始识别Date date2 = fastDateFormat.parse("日期:2020-01-08",new ParsePosition(3));// 第三个参数有点复杂,有时间自己去研究
parseObject() 字符串转换成未知对象
FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd");// 不太理解为什么要转成 ObjectDate date = (Date)fastDateFormat.parseObject("日期:2020-01-08", new ParsePosition(3));
getLocale() 获取区域的信息getTimeZone() 获取时区信息getPattern() 获取格式信息getMaxLengthEstimate() 获取格式化字符串最大长度不能直接实例化,需要通过继承的方式实现功能
FastDateParser
public class MyFastDateParser extends FastDateParser {// 必须实现,且设置为 publicpublic MyFastDateParser(String pattern, TimeZone timeZone, Locale locale) {super(pattern, timeZone, locale);}// 必须实现,且设置为 publicpublic MyFastDateParser(String pattern, TimeZone timeZone, Locale locale, Date centuryStart) {super(pattern, timeZone, locale, centuryStart);}}
parse() 字符串转换成日期对象
FastDateParser myFastDateParser = new MyFastDateParser("yyyy-MM-dd",TimeZone.getDefault(),Locale.CHINA);// 按照格式识别成日期对象Date date1 = myFastDateParser.parse("2020-01-08");// 从第四个字符开始识别Date date2 = myFastDateParser.parse("日期:2020-01-08",new ParsePosition(3));// 第三个参数有点复杂,有时间自己去研究
parseObject() 字符串转换成未知对象
FastDateParser myFastDateParser = new MyFastDateParser("yyyy-MM-dd",TimeZone.getDefault(),Locale.CHINA);// 不太理解为什么要转成 ObjectDate date = (Date)myFastDateParser.parseObject("日期:2020-01-08", new ParsePosition(3));
getLocale() 获取区域的信息getTimeZone() 获取时区信息getPattern() 获取格式信息不能直接实例化,需要通过继承的方式实现功能
FastDatePrinter
public class MyFastDatePrinter extends FastDatePrinter {// 必须实现,且设置为 publicpublic MyFastDatePrinter(String pattern, TimeZone timeZone, Locale locale) {super(pattern, timeZone, locale);}}
format() 时间格式化
// 时间long time = System.currentTimeMillis();// 结果容器StringBuilder sb = new StringBuilder();FastDatePrinter myFastDatePrinter = new MyFastDatePrinter("yyyy-MM-dd",TimeZone.getDefault(),Locale.CHINA);// 结果:2020-01-09System.out.println(myFastDatePrinter.format(time));// 结果:2020-01-09System.out.println(myFastDatePrinter.format(time,sb));// 结果:2020-01-09System.out.println(sb);
getLocale() 获取区域的信息getTimeZone() 获取时区信息getPattern() 获取格式信息getMaxLengthEstimate() 获取格式化字符串最大长度static getGmtTimeZone() 获取GMT时区static getTimeZone() 通过id获取时区static createStarted() 创建并启动一个秒表
StopWatch started = StopWatch.createStarted();
getStartTime() 获取秒表开始时的时间戳
StopWatch started = StopWatch.createStarted();// 结果:1578536764556System.out.println(started.getStartTime());
getTime() 获取秒表的时间间隔
StopWatch started = StopWatch.createStarted();Thread.sleep(1000);// 默认是毫秒,结果:1009System.out.println(started.getTime());// 设置成微妙:结果:1009734System.out.println(started.getTime(TimeUnit.MICROSECONDS));
getNanoTime() 获取秒表的时间间隔(纳秒)
StopWatch started = StopWatch.createStarted();Thread.sleep(1000);// 结果:1004136700System.out.println(started.getNanoTime());// 结果:1004312400System.out.println(started.getNanoTime());
split() 拆分秒表
StopWatch started = StopWatch.createStarted();// 拆分没有返回值started.split();
unsplit() 消除拆分
StopWatch started = StopWatch.createStarted();// 必须拆分started.split();// 消除started.unsplit();
getSplitTime() 获取拆分秒表的时间间隔(毫秒)
StopWatch started = StopWatch.createStarted();Thread.sleep(1000);// 拆分started.split();// 结果:1004System.out.println(started.getSplitTime());
getSplitNanoTime() 获取拆分秒表的时间间隔(纳秒)
StopWatch started = StopWatch.createStarted();Thread.sleep(1000);// 拆分started.split();// 结果:1007609400System.out.println(started.getSplitNanoTime());
stop() 停止
StopWatch started = StopWatch.createStarted();// 停止started.split();
reset() 重置
StopWatch started = StopWatch.createStarted();// 必须停止started.split();// 重置started.reset();
start() 启动
StopWatch started = StopWatch.createStarted();// 停止started.split();// 必须重置started.reset();// 启动started.start();
suspend() 暂停resume() 恢复
StopWatch started = StopWatch.createStarted();// 暂停started.suspend();
resume() 恢复
StopWatch started = StopWatch.createStarted();// 必须暂停started.suspend();// 恢复started.resume();
isStarted() 是否启动
StopWatch started = StopWatch.createStarted();// 结果:trueSystem.out.println(started.isStarted());// 停止started.stop();// 结果:falseSystem.out.println(started.isStarted());
isStopped() 是否停止
StopWatch started = StopWatch.createStarted();// 结果:falseSystem.out.println(started.isStopped());// 停止started.stop();// 结果:trueSystem.out.println(started.isStopped());
isSuspended() 是否暂停
StopWatch started = StopWatch.createStarted();// 结果:falseSystem.out.println(started.isSuspended());// 暂停started.suspend();// 结果:trueSystem.out.println(started.isSuspended());
static GMT_ID GMT
exception 异常工具类
event 事件工具类
builder
concurrent 并发工具类
math 算数工具类
mutable
reflect 反射工具类
status getAccessibleConstructor() 检验构造函数可访问性
// 通过当前方法可获取一个构造函数类Constructor<TestParent> accessibleConstructor = ConstructorUtils.getAccessibleConstructor(TestParent.class);// Test的无参构造函被覆盖了,结果:nullSystem.out.println(ConstructorUtils.getAccessibleConstructor(Test.class));// 结果:nullSystem.out.println(ConstructorUtils.getAccessibleConstructor(Test.class,String.class));// 成功找到一个带Object参数的构造函数,结果:public com.lidaye.demo.Test(java.lang.Object)System.out.println(ConstructorUtils.getAccessibleConstructor(Test.class,Object.class));// 通过构造函数类重新获取,结果:public com.lidaye.demo.TestParent()System.out.println(ConstructorUtils.getAccessibleConstructor(accessibleConstructor));
status getMatchingAccessibleConstructor() 检验构造函数可访问性(参数类型兼容)
// Test的无参构造函被覆盖了,结果:nullSystem.out.println(ConstructorUtils.getMatchingAccessibleConstructor(Test.class));// 兼容到 Object 的带参构造,结果:public com.lidaye.demo.Test(java.lang.Object)System.out.println(ConstructorUtils.getMatchingAccessibleConstructor(Test.class,String.class));// 结果:public com.lidaye.demo.Test(java.lang.Object)System.out.println(ConstructorUtils.getMatchingAccessibleConstructor(Test.class,Object.class));
status invokeConstructor() 通过构造函数取对象实例(参数类型兼容)
try {// 报错:No such accessible constructor on object: com.lidaye.demo.TestSystem.out.println(ConstructorUtils.invokeConstructor(Test.class));// 结果:Test{name='李大爷'}System.out.println(ConstructorUtils.invokeConstructor(Test.class,"李大爷"));// 结果:Test{name='李学霸'}System.out.println(ConstructorUtils.invokeConstructor(Test.class,new String[]{"李学霸"},new Class[]{String.class}));} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}
status invokeExactConstructor() 通过构造函数取对象实例
try {// 报错:No such accessible constructor on object: com.lidaye.demo.TestSystem.out.println(ConstructorUtils.invokeExactConstructor(Test.class));// 报错:No such accessible constructor on object: com.lidaye.demo.TestSystem.out.println(ConstructorUtils.invokeExactConstructor(Test.class,"李大爷"));// 结果:Test{name='李学霸'}System.out.println(ConstructorUtils.invokeExactConstructor(Test.class,new String[]{"李学霸"},new Class[]{Object.class}));// 报错:No such accessible constructor on object: com.lidaye.demo.TestSystem.out.println(ConstructorUtils.invokeExactConstructor(Test.class,new Object[]{"李学霸"},new Class[]{String.class}));// 结果:Test{name='李学霸'}System.out.println(ConstructorUtils.invokeExactConstructor(Test.class,new Object[]{"李学霸"},new Class[]{Object.class}));} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}
tuple 元组工具类
text