目录
- 1.引入pom依赖
- 2. 工具类的使用
- ==2.1 Assert 断言==
- `2.1.1 Assert.notNull:要求参数必须为非Null`
- `2.1.2 Assert.isNull: 要求参数必须为Null`
- `2.1.3 Assert.notEmpty: 要求参数(Collection<?>||Map||Array[])必须非空非Null`
- `2.1.4 Assert.isTrue: 要求参数必须为真(True)`
- `2.1.5 Assert.hasLength: 要求参数(String)必须有长度(即,Not Empty)`
- `2.1.6 Assert.hasText: 要求参数(String)必须有内容(即,Not Blank)`
- `2.1.7 Assert.isInstanceOf: 要求参数是指定类型的实例`
- `2.1.8 Assert.isAssignable: 要求入参实例对象必须是入参类对象的子类或实现类`
- `2.1.9 Assert.state: 断言一个 boolean表达式 如果为false 则抛出异常(跟isTrue没啥区别)`
- `2.1.10 Assert.noNullElements: 断言数组或集合中是否存在null`
- `2.1.11 Assert.doesNotContain: 断言给定的文本不包含给定的子字符串`
- ==2.2 CollectionUtils 操作工具==
- `2.2.1 CollectionUtils.isEmpty: 判断 Collection || Map 是否为空或null`
- `2.2.2 CollectionUtils.containsInstance: 判断 Collection 中是否包含某个对象`
- `2.2.3 CollectionUtils.containsAny: 判断 Collection中 是否包含某些对象中的任意一个`
- `2.2.4 CollectionUtils.hasUniqueObject: 判断 Collection中的每个元素是否唯一`
- `2.2.5 CollectionUtils.findFirstMatch: 返回 List ||Set 第一个元素`
- `2.2.6 CollectionUtils.lastElement: 返回 List ||Set 最后一个元素`
- `2.2.7 CollectionUtils.findCommonElementType: 查找返回给定集合的公共元素类型(如果有)`
- ==2.3 FileCopyUtils 文件操作工具==
- ==2.4 ResourceUtils 资源操作工具==
- ==2.5 StreamUtils IO 流操作工具==
- ==2.6 ObjectUtils 对象、数组、集合操作工具==
- `2.6.1 ObjectUtils.nullSafeClassName: 获取对象的类名`
- `2.6.2 ObjectUtils.nullSafeHashCode: 获取对象的hashCode`
- `2.6.3 ObjectUtils.nullSafeToString: 返回指定对象的字符串表示形式`
- `2.6.4 ObjectUtils.getIdentityHexString: 获取对象 HashCode(十六进制形式字符串)`
- `2.6.5 ObjectUtils.identityToString: 获取对象的类名和 HashCode`
- `2.6.6 ObjectUtils.identityToString: 打印地址 toString方法 如果是 数组或集合则打印值 参数为 null 时,返回字符串:""`
- `2.6.7 ObjectUtils.addObjectToArray: 将给定对象附加到给定数组`
- `2.6.8 ObjectUtils.caseInsensitiveValueOf: 忽略大小写获取指定的枚举对象`
- `2.6.9 ObjectUtils.containsConstant: 检查给定的枚举常量数组是否包含具有给定名称的常量`
- `2.6.10 ObjectUtils.toObjectArray: 将给定数组(可能是原始数组)转换为对象数组(如果需要原始包装对象)`
- `2.6.11 ObjectUtils.unwrapOptional: 解包Optional `
- `2.6.12 ObjectUtils.isEmpty: 判断对象是否为空 `
- `2.6.13 ObjectUtils.isArray: 确定给定对象是否为数组 `
- `2.6.14 ObjectUtils.containsElement: 判断给定数组是否包含给定元素 `
- `2.6.15 ObjectUtils.nullSafeEquals: 确定给定对象是否相等;数组和集合基于元素比较 `
- ==2.7 StringUtils 字符串操作工具==
- `2.7.1 StringUtils.isEmpty: 判断字符串是否为 null,或 ""`
- `2.7.2 StringUtils.hasLength: 判断字符串非空且长度不为 0,即,Not Empty`
- `2.7.3 StringUtils.hasText: 判断字符串是否包含实际内容,即非仅包含空白符,也就是 Not Blank`
- `2.7.4 StringUtils.endsWithIgnoreCase: 判断字符串是否是以指定内容结束。忽略大小写`
- `2.7.5 StringUtils.startsWithIgnoreCase: 判断字符串是否已指定内容开头。忽略大小写`
- `2.7.6 StringUtils.containsWhitespace: 是否包含空白符`
- `2.7.7 StringUtils.substringMatch: 判断字符串指定索引处是否包含一个指定子串`
- `2.7.8 StringUtils.countOccurrencesOf: 计算一个字符串中指定子串的出现次数`
- `2.7.9 StringUtils.replace: 查找并替换指定子串`
- `2.7.10 StringUtils.trimTrailingCharacter: 去除尾部的特定字符`
- `2.7.11 StringUtils.trimLeadingCharacter: 去除头部的特定字符`
- `2.7.12 StringUtils.trimLeadingWhitespace: 去除头部的空白符`
- `2.7.13 StringUtils.trimTrailingWhitespace: 去除尾部的空白符`
- `2.7.14 StringUtils.trimWhitespace: 去除头部和尾部的空白符`
- `2.7.15 StringUtils.trimAllWhitespace: 去除字符串中所有的空白符`
- `2.7.16 StringUtils.delete: 删除所有出现的给定子字符串`
- `2.7.17 StringUtils.deleteAny: 删除给定字符串中的任何字符`
- `2.7.18 StringUtils.trimArrayElements: 对数组的每一项执行 trim() 方法(删除前端和尾端的空白字符)`
- `2.7.19 StringUtils.addStringToArray: 将给定的字符串附加到给定的字符串数组中`
- `2.7.20 StringUtils.arrayToCommaDelimitedString: 将入参数组转换为逗号分隔的字符串返回`
- `2.7.21 StringUtils.arrayToDelimitedString: 将入参数组转换为指定分隔符进行分隔 并转为字符串返回`
- `2.7.22 StringUtils.collectionToCommaDelimitedString: 将入参集合转换为逗号分隔符进行分隔 并转为字符串返回`
- `2.7.23 StringUtils.collectionToCommaDelimitedString: 将入参集合转换为指定分隔符进行分隔 并转为字符串返回`
- `2.7.24 StringUtils.capitalize: 将第一个字母更改为大写`
- `2.7.25 StringUtils.uncapitalize: 取消大写 将第一个字母更改为小写。其他字母没有变化`
- `2.7.26 StringUtils.getFilenameOrgetFilenameExtension: 规范化路径 OR 获取路径上的附件名 OR 文件扩展名`
- `2.7.27 StringUtils.pathEquals: 在对它们进行cleanPath(规范化)后比较两条路径`
- `2.7.28 StringUtils.parseTimeZoneString: 获取 TimeZone时区`
- `2.7.29 StringUtils.quote: 用单引号引用给定的值`
- `2.7.30 StringUtils.removeDuplicateStrings: 从给定的数组中删除重复的字符串`
- `2.7.31 StringUtils.sortStringArray: 如有必要,对给定的 入参数组进行排序(升序)。`
- `2.7.32 StringUtils.split: 在指定分隔符的第一次出现处拆分,结果中不包含分隔符。(只拆分一次)`
- `2.7.33 StringUtils.unqualify: 获取入参制定分隔符最后的一部分`
- ==2.8 ReflectionUtils 反射、AOP操作工具==
- `2.8.1 ReflectionUtils.findMethod: 在类中查找指定方法`
- `2.8.2 ReflectionUtils.getAllDeclaredMethods: 获得类中所有方法,包括继承而来的`
- `2.8.3 ReflectionUtils.getDeclaredMethods: 获得类中所有方法,不包括继承而来的`
- `2.8.4 ReflectionUtils.accessibleConstructor: 在类中查找指定构造方法`
- `2.8.5 ReflectionUtils.declaresException: 检查一个方法是否声明抛出指定异常`
- `2.8.6 ReflectionUtils.invokeMethod: 执行方法`
- `2.8.7 ReflectionUtils.makeAccessible: 取消 Java 权限检查。后续执行私有方法`
- `2.8.8 ReflectionUtils.findField: 在类中查找指定属性`
- `2.8.9 ReflectionUtils.isPublicStaticFinal: 是否为一个 "public static final" 属性`
- `2.8.10 ReflectionUtils.getField: 获取传入对象的指定字段值`
- `2.8.11 ReflectionUtils.setField: 设置 传入对象的 指定 字段值`
- `2.8.12 ReflectionUtils.shallowCopyFieldState: 同类对象属性对等赋值`
- `2.8.13 ReflectionUtils.doWithFields: 对指定类的每个字段执行前 回调doWith(包括继承而来的字段)`
- `2.8.14 ReflectionUtils.doWithLocalFields: 对指定类的每个字段执行前 回调doWith(不包含继承而来的字段)`
- `2.8.15 ReflectionUtils.doWithMethods: 对指定类的每个方法执行前 回调doWith(包括继承而来的方法)`
- `2.8.16 ReflectionUtils.doWithLocalMethods: 对指定类的每个方法执行前 回调doWith(不包括继承而来的方法)`
- `2.8.17 ReflectionUtils.getUniqueDeclaredMethods: 对象之间的copy 复制所有字段,包括继承的字段`
- `2.8.18 ReflectionUtils.clearCache: 清空缓存,每次查询(方法,参数)时都会做缓存`
- 链接:[SpringBoot之自带工具类常用示例 源代码下载地址](https://download.csdn.net/download/JAVA_MHH/85239177)
1.引入pom依赖
- 因都是springboot自带的工具类 不需要引用其它pom依赖
<!--引入springboot父工程依赖-->
<!--引入依赖作用:
可以省去version标签来获得一些合理的默认配置
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
</parent>
<dependencies>
<!--两个用来做测试的jar包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
2. 工具类的使用
2.1 Assert 断言
- 断言是一个逻辑判断,用于检查不应该发生的情况
2.1.1 Assert.notNull:要求参数必须为非Null
- 要求参数 object 必须为非Null(Not Null),否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数 object 必须为非Null(Not Null),否则抛出异常,不予放行
// 参数 message 参数用于定制异常信息。
@Test
public void notNull() {
Assert.notNull(new ArrayList<>(), "集合不能为null");//通过(只校验是否为null)
String s = null;
Assert.notNull(s, "字符串不能为null");//java.lang.IllegalArgumentException: 不能为null
}
}
2.1.2 Assert.isNull: 要求参数必须为Null
- 要求参数必须为Null,否则抛出异常,不予『放行』。
- 和 notNull() 方法断言规则相反
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数必须为Null,否则抛出异常,不予『放行』。
// 和 notNull() 方法断言规则相反
@Test
public void isNull() {
String s=null;
Assert.isNull(s,"字符串必须为null");
s="";
Assert.isNull(s,"这里字符串必须为null");//java.lang.IllegalArgumentException: 这里字符串必须为null
}
}
2.1.3 Assert.notEmpty: 要求参数(Collection<?>||Map||Array[])必须非空非Null
- 要求参数(Collection<?>||Map||Array[])必须非空非Null(Not Empty),否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数(Collection<?>||Map||Array[])必须非空非Null(Not Empty),否则抛出异常,不予放行
// 参数 message 参数用于定制异常信息
@Test
public void notEmpty() {
Assert.notEmpty(new ArrayList<>(), "List不能为null 为空");//java.lang.IllegalArgumentException: List不能为null 为空
String[] i = {};
Assert.notEmpty(i, "数组不能为null 为空");//java.lang.IllegalArgumentException: 数组不能为null 为空
Assert.notEmpty(new HashMap<>(), "Map不能为null 为空");//java.lang.IllegalArgumentException: Map不能为null 为空
}
}
2.1.4 Assert.isTrue: 要求参数必须为真(True)
- 要求参数必须为真(True),否则抛出异常,不予『放行』。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数必须为真(True),否则抛出异常,不予『放行』。
@Test
public void isTrue(){
Boolean b = true;//如果里是null 那么会报空指针异常
Assert.isTrue(b,"boolean必须为true");
b=false;
Assert.isTrue(b,"这里boolean必须为true");//java.lang.IllegalArgumentException: 这里boolean必须为true
}
}
2.1.5 Assert.hasLength: 要求参数(String)必须有长度(即,Not Empty)
- 要求参数(String)必须有长度(即,Not Empty),否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数(String)必须有长度(即,Not Empty),否则抛出异常,不予放行
@Test
public void hasLength(){
String s=" ";
Assert.hasLength(s,"字符串必须有长度");
s="";
Assert.hasLength(s,"这里字符串必须有长度");//java.lang.IllegalArgumentException: 这里字符串必须有长度
}
}
2.1.6 Assert.hasText: 要求参数(String)必须有内容(即,Not Blank)
- 要求参数(String)必须有内容(即,Not Blank)空格也不行,否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数(String)必须有内容(即,Not Blank)空格也不行,否则抛出异常,不予放行
@Test
public void hasText(){
String s=" 12";
Assert.hasText(s,"字符串必须有值");
s=" ";
Assert.hasText(s,"这里字符串必须有值");//java.lang.IllegalArgumentException: 这里字符串必须有值
}
}
2.1.7 Assert.isInstanceOf: 要求参数是指定类型的实例
- 要求参数是指定类型的实例,否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数是指定类型的实例,否则抛出异常,不予放行
@Test
public void isInstanceOf(){
List<String> list = new ArrayList<>();
Assert.isInstanceOf(ArrayList.class, list, "此参数不是指定类型的实例");
Assert.isInstanceOf(Collector.class,list);//java.lang.IllegalArgumentException: Object of class [java.util.ArrayList] must be an instance of interface java.util.stream.Collector
//java.lang.IllegalArgumentException:类 [java.util.ArrayList] 的对象必须是接口 java.util.stream.Collector 的实例
}
}
2.1.8 Assert.isAssignable: 要求入参实例对象必须是入参类对象的子类或实现类
- 要求入参实例对象必须是入参类对象的子类或实现类,否则抛出异常,不予放行
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
// 要求参数 `subType` 必须是参数 superType 的子类或实现类,否则抛出异常,不予放行
@Test
public void isAssignable() {
String s= "";
Assert.isAssignable(String.class, s.getClass());//通过
Assert.isAssignable(Object.class, s.getClass());//通过
Assert.isAssignable(Integer.class,s.getClass());//java.lang.IllegalArgumentException: class java.lang.String is not assignable to class java.lang.Integer
}
}
2.1.9 Assert.state: 断言一个 boolean表达式 如果为false 则抛出异常(跟isTrue没啥区别)
- 断言一个 boolean表达式 如果为false 则抛出异常(跟isTrue没啥区别)
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
//断言一个 boolean表达式 如果为false 则抛出异常(跟isTrue没啥区别)
@Test
public void state() {
int i=0;
Assert.state(i==0,"i!=0");
// Assert.isTrue(i==0,"i!=0");//java.lang.IllegalStateException: i!=0
Assert.state(i!=0,"i!=0");//java.lang.IllegalStateException: i!=0
}
}
2.1.10 Assert.noNullElements: 断言数组或集合中是否存在null
- 断言数组或集合中是否存在null 如果有 null则报错
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
//断言数组或集合中是否存在null 如果有 null则报错
@Test
public void noNullElements(){
String []s ={"1","2","3"};
Assert.noNullElements(s, "数组中存在 null的元素");
s[1]=null;
System.err.println(Arrays.toString(s));//[1, null, 3]
Assert.noNullElements(s, "数组中存在 null的元素");//java.lang.IllegalArgumentException: 数组中存在 null的元素
//--------------------------------------------------------------------------------------------------------
List<String> list =new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
Assert.noNullElements(list, "集合中存在 null的元素");
list.add(null);
System.err.println(list);//[1, 2, 3, null]
Assert.noNullElements(list, "集合中存在 null的元素");//java.lang.IllegalArgumentException: 集合中存在 null的元素
}
}
2.1.11 Assert.doesNotContain: 断言给定的文本不包含给定的子字符串
- 断言给定的文本不包含给定的子字符串 如果有 则报错
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.util.*;
import java.util.stream.Collector;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: 断言相关方法
*/
@SpringBootTest
//@RunWith(SpringRunner.class)
public class AssertTest {
//断言给定的文本不包含给定的子字符串(如果包含则报异常)
@Test
public void doesNotContain(){
Assert.doesNotContain("123", "34", "此文本包含给定的子字符串");
Assert.doesNotContain("123","23","这里此文本包含给定的子字符串");//java.lang.IllegalArgumentException: 这里此文本包含给定的子字符串
}
}
2.2 CollectionUtils 操作工具
2.2.1 CollectionUtils.isEmpty: 判断 Collection || Map 是否为空或null
- 判断 Collection || Map 是否为空或null
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
// 判断 Collection||Map 是否为空
@Test
public void isEmpty() {
List<Object> list=null;
System.err.println(CollectionUtils.isEmpty(list));//true
System.err.println(CollectionUtils.isEmpty(new ArrayList<>()));//true
System.err.println(CollectionUtils.isEmpty(Arrays.asList("1", "2")));//false
System.err.println(CollectionUtils.isEmpty(new HashMap<>()));//true
Map<Object, Object> map = new HashMap<>();
map.put("name", "mhh");
System.err.println(CollectionUtils.isEmpty(map));//false
}
}
2.2.2 CollectionUtils.containsInstance: 判断 Collection 中是否包含某个对象
- 判断 Collection 中是否包含某个对象
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
// 判断 Collection 中是否包含某个对象
@Test
public void containsInstance() {
System.err.println(CollectionUtils.
containsInstance(Arrays.asList("A", "b", "c"), "a"));//false
System.err.println(CollectionUtils.
containsInstance(Arrays.asList("A", "b", "c"), "c"));//true
}
}
2.2.3 CollectionUtils.containsAny: 判断 Collection中 是否包含某些对象中的任意一个
- 判断 Collection中 是否包含某些对象中的任意一个
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
//判断 Collection 是否包含某些对象中的任意一个
@Test
public void containsAny() {
System.err.println(CollectionUtils.
containsAny(Arrays.asList("1", "2", "3"), Arrays.asList("2", "4")));//true
System.err.println(CollectionUtils.
containsAny(Arrays.asList("1", "2", "3"), Arrays.asList("0", "4")));//false
}
}
2.2.4 CollectionUtils.hasUniqueObject: 判断 Collection中的每个元素是否唯一
- 判断 Collection中的每个元素是否唯一(唯一为false)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
//判断 Collection中的每个元素是否唯一。
@Test
public void hasUniqueObject() {
System.err.println(CollectionUtils.hasUniqueObject(Arrays.asList("1", "2", "3")));//false
System.err.println(CollectionUtils.hasUniqueObject(Arrays.asList("1", "1")));//true
}
}
2.2.5 CollectionUtils.findFirstMatch: 返回 List ||Set 第一个元素
- 返回 List ||Set 第一个元素
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
//返回 List ||Set 第一个元素
@Test
public void findFirstMatch() {
System.err.println(CollectionUtils.firstElement(Arrays.asList("1", "2", "3"))); // 1
System.err.println(CollectionUtils.firstElement(Arrays.asList(3,2,1))); // 3
}
}
2.2.6 CollectionUtils.lastElement: 返回 List ||Set 最后一个元素
- 返回 List ||Set 最后一个元素
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
// 返回 List ||Set 中最后一个元素
@Test
public void lastElement() {
System.err.println(CollectionUtils.lastElement(Arrays.asList("1", "2", "3"))); //3
System.err.println(CollectionUtils.lastElement(Arrays.asList(3,2,1))); //3
}
}
2.2.7 CollectionUtils.findCommonElementType: 查找返回给定集合的公共元素类型(如果有)
- 查找给定集合的公共元素类型(如果有)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 集合工具
*/
@SpringBootTest
public class CollectionUtilsTest {
//查找给定集合的公共元素类型(如果有)
@Test
public void findCommonElementType() {
System.err.println(CollectionUtils.
findCommonElementType(Arrays.asList("1", "2")));// class java.lang.String
System.err.println(CollectionUtils.
findCommonElementType(Arrays.asList(1, 2))); //class java.lang.Integer
System.err.println(CollectionUtils.
findCommonElementType(Arrays.asList("1", new Object()))); //null
System.err.println(CollectionUtils.
findCommonElementType(Arrays.asList(new Object(), new Object()))); //class java.lang.Object
}
}
2.3 FileCopyUtils 文件操作工具
2.3.1 FileCopyUtils.copyToByteArray: 将文件的内容复制到一个新的字节数组中
- 从文件中或流中读入到字节数组中
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.FileCopyUtils;
import java.io.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 文件操作工具
*/
@SpringBootTest
public class FileCopyUtilsTest {
// 从文件中读入到字节数组中
@Test
public void copyToByteArray() throws IOException {
File file = new File("D:\\a.jpg");
System.err.println(FileCopyUtils.copyToByteArray(file).length); // 209
InputStream inputStream = new FileInputStream(file);
System.err.println(FileCopyUtils.copyToByteArray(inputStream).length);// 209
System.err.println(new String(FileCopyUtils.copyToByteArray(new File("D:\\a.txt"))));//123mhh
}
}
2.3.2 FileCopyUtils.copyToString: 将文件的内容复制到一个新的字符串中
- 将读入到的内容复制到 String 中
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.FileCopyUtils;
import java.io.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 文件操作工具
*/
@SpringBootTest
public class FileCopyUtilsTest {
//将读入到的内容复制到 String 中。完成后关闭Reader。
@Test
public void copyToString() throws IOException {
FileReader fileReader = new FileReader("D:\\a.txt");
System.err.println(FileCopyUtils.copyToString(fileReader)); // 123mhh
}
}
2.3.3 FileCopyUtils.copyToString: 将给定输入文件的内容复制到给定输出文件。
- 附件的copy (输出的附件不存在则会自动创建)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.FileCopyUtils;
import java.io.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/14
* @描述: 文件操作工具
*/
@SpringBootTest
public class FileCopyUtilsTest {
//附件的Copy
@Test
public void copy() throws IOException {
//将给定输入文件的内容复制到给定输出文件。
System.err.println(FileCopyUtils.copy(
new File("D:\\a.txt"),
new File("D:\\b.txt")));//6
//将给定 InputStream 的内容复制到给定 OutputStream。完成后关闭两个流。
System.err.println(FileCopyUtils.copy(
new FileInputStream(new File("D:\\a.txt")),
new FileOutputStream(new File("D:\\b.txt"))));//6
//将给定 Reader 的内容复制到给定 Writer。完成后关闭两者。
System.err.println(FileCopyUtils.copy(
new FileReader(new File("D:\\a.txt")),
new FileWriter(new File("D:\\b.txt"))));//6
}
}
2.4 ResourceUtils 资源操作工具
2.4.1 ResourceUtils: 从资源路径获取文件
isUrl:
判断字符串是否是一个合法的 URL 字符串。getURL:
获取 URLgetFile:
获取文件(在 JAR 包内无法正常使用,需要是一个独立的文件)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 资源操作工具
*/
@SpringBootTest
public class ResourceUtilsTest {
// 判断字符串是否是一个合法的 URL 字符串。
@Test
public void isUrl() {
System.err.println(ResourceUtils.isUrl("https://www.baidu.com/img/flexible/logo/pc/result.png")); //true
System.err.println(ResourceUtils.isUrl("mhh")); //false
}
// 获取 URL
@Test
public void getURL() throws FileNotFoundException {
URL url = ResourceUtils.getURL("https://www.baidu.com/img/flexible/logo/pc/result.png");
System.err.println(url.toString());//https://www.baidu.com/img/flexible/logo/pc/result.png
}
// 获取文件(在 JAR 包内无法正常使用,需要是一个独立的文件(即文件系统中的文件) )
@Test
public void getFile() throws FileNotFoundException {
File file = ResourceUtils.getFile("D:\\a.txt");
System.err.println(file.length()); //10
}
}
2.4.2 UrlResource: URL 资源(如 file://... http://...)
exists:
判断资源是否存在getURI:
从资源中获得 URI 对象getURL:
从资源中获得 URL 对象getInputStream
: 获得资源的 InputStreamgetDescription
: 获得资源的描述信息getFilename
: 此实现返回此 URL 引用的文件的名称。contentLength
: 资源大小lastModified
: 资源生成的时间戳
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 资源操作工具
*/
@SpringBootTest
public class ResourceUtilsTest {
//------------------------- UrlResource // URL 工具资源,如 file://... http://... ----------------------------------------------------------------------
@Test
public void UrlResource() throws IOException {
// 判断资源是否存在
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").exists());//true
System.err.println(new UrlResource("https://www.baidu.com/abc.txt").exists());//false
// 从资源中获得 URI 对象
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getURI());//https://www.baidu.com/img/flexible/logo/pc/result.png
// 从资源中获得 URL 对象
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getURL());//https://www.baidu.com/img/flexible/logo/pc/result.png
// 获得资源的 InputStream
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getInputStream());//sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6d3a388c
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getInputStream());//sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6d3a388c
// 获得资源的描述信息
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getDescription());//URL [https://www.baidu.com/img/flexible/logo/pc/result.png]
//此实现返回此 URL 引用的文件的名称。
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").getFilename());// result.png
//资源大小
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").contentLength());//6617
//资源生成的时间戳
System.err.println(new UrlResource("https://www.baidu.com/img/flexible/logo/pc/result.png").lastModified());//1589016836000
}
}
2.4.3 FileSystemResource 文件系统资源 (如 D:\\...)
exists:
判断资源是否存在getURI:
从资源中获得 URI 对象getURL:
从资源中获得 URL 对象getInputStream
: 获得资源的 InputStreamgetOutputStream
: 获得资源的 OutputStream(注意 会将原附件数据清空)getDescription
: 获得资源的描述信息getFilename
: 此实现返回此 URL 引用的文件的名称。contentLength
: 资源大小lastModified
: 资源生成的时间戳
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 资源操作工具
*/
@SpringBootTest
public class ResourceUtilsTest {
//---------------------- FileSystemResource 文件系统资源 D:\\...-------------------------
@Test
public void FileSystemResource() throws IOException {
// 判断资源是否存在
System.err.println(new FileSystemResource("D:\\a.txt").exists());//true
System.err.println(new FileSystemResource("D:\\a.png").exists());//false
// 从资源中获得 URI 对象
System.err.println(new FileSystemResource("D:\\a.txt").getURI());// file:/D:/a.txt
// 从资源中获得 URL 对象
System.err.println(new FileSystemResource("D:\\a.txt").getURL());// file:/D:/a.txt
// 获得资源的 InputStream
System.err.println(new FileSystemResource("D:\\a.txt").getInputStream());//sun.nio.ch.ChannelInputStream@7403c468
// 获得资源的 OutputStream(注意 会将原附件数据清空)
System.err.println(new FileSystemResource("D:\\a.txt").getOutputStream());//java.nio.channels.Channels$1@4d9754a8
// 获得资源的描述信息
System.err.println(new FileSystemResource("D:\\a.txt").getDescription());// file [D:\a.txt]
//此实现返回此资源 引用的文件的名称。
System.err.println(new FileSystemResource("D:\\a.txt").getFilename());// a.txt
//资源大小
System.err.println(new FileSystemResource("D:\\a.txt").contentLength());//6
//资源生成的时间戳
System.err.println(new FileSystemResource("D:\\a.txt").lastModified());//1649937444715
}
}
2.4.4 ClassPathResource 类路径下的资源 (如:classpth:...)
exists:
判断资源是否存在getURI:
从资源中获得 URI 对象getURL:
从资源中获得 URL 对象getFile
: 获得资源的 filegetInputStream
: 获得资源的 InputStreamgetDescription
: 获得资源的描述信息getFilename
: 此实现返回此 URL 引用的文件的名称。contentLength
: 资源大小lastModified
: 资源生成的时间戳
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 资源操作工具
*/
@SpringBootTest
public class ResourceUtilsTest {
//----------------------------- // 类路径下的资源,classpth:... --------------------------------
// 类路径下的资源 classpth:...
@Test
public void ClassPathResource() throws IOException {
// 判断资源是否存在
System.err.println(new ClassPathResource("application.yml").exists());//true
System.err.println(new ClassPathResource("application-dev.yml").exists());//false
// 从资源中获得 URI 对象
System.err.println(new ClassPathResource("application.yml").getURI());// file:/D:/codebase/biz/springboot_own_tools/target/classes/application.yml
// 从资源中获得 URL 对象
System.err.println(new ClassPathResource("application.yml").getURL());// file:/D:/codebase/biz/springboot_own_tools/target/classes/application.yml
// 获得资源的 file
System.err.println(new ClassPathResource("application.yml").getFile());// D:\codebase\biz\springboot_own_tools\target\classes\application.yml
// 获得资源的 InputStream
System.err.println(new ClassPathResource("application.yml").getInputStream());//java.io.BufferedInputStream@2db7a79b
// 获得资源的描述信息
System.err.println(new ClassPathResource("application.yml").getDescription());// class path resource [application.yml]
//此实现返回此资源 引用的文件的名称。
System.err.println(new ClassPathResource("application.yml").getFilename());// application.yml
//资源大小
System.err.println(new ClassPathResource("application.yml").contentLength());//55
//资源生成的时间戳
System.err.println(new ClassPathResource("application.yml").lastModified());//1649989411561
}
}
2.5 StreamUtils IO 流操作工具
2.5.1 StreamUtils.copy: 将给定入参的内容复制到给定流中。
int copy(InputStream in, OutputStream out):
将给定 InputStream 的内容复制到给定 OutputStream.(完成后让两个流都打开)void copy(byte[] in, OutputStream out):
将给定字节数组的内容复制到给定的 OutputStream. (完成后保持流打开)void copy(String in, Charset charset, OutputStream out):
将给定 String 的内容复制到给定的 OutputStream.(完成后保持流打开)
in: 要从中复制的字符串
charset: 字符集
out: 要从中复制的字符串
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: StreamUtils IO 流操作工具
*/
public class StreamUtilsTest {
//附件复制
@Test
public void copy() throws IOException {
InputStream inputStream = new FileSystemResource("D:\\a.txt").getInputStream();
OutputStream outputStream = new FileSystemResource("D:\\b.txt").getOutputStream();
StreamUtils.copy(inputStream, outputStream);
byte[] bytes = StreamUtils.copyToByteArray(inputStream);
StreamUtils.copy(bytes, outputStream);
//将给定 String 的内容复制到给定的 OutputStream
// in:要从中复制的字符串
// charset: 字符集
// out:要复制到的 OutputStream
StreamUtils.copy("mhh", Charset.defaultCharset(), outputStream);
//注意 流还是开着的,需要手动关闭。
outputStream.close();
inputStream.close();
}
}
2.5.2 StreamUtils.copyRange: 将给定入参的指定内容长度复制到给定流中(如果入参值超过指定内容长度则返回实际复制的字节数)
long copyRange(InputStream in, OutputStream out, long start, long end)
将给定 InputStream 的内容范围复制到给定 OutputStream, 如果指定范围超过 InputStream 的长度,则复制到流的末尾并返回实际复制的字节数, 完成后让两个流都打开。
in: 要从中复制的 InputStream
out: 要复制到的 OutputStream
start: 开始复制的位置
end: 结束复制的位置
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: StreamUtils IO 流操作工具
*/
public class StreamUtilsTest {
//附件复制
@Test
public void copy() throws IOException {
//复制指定长度附件
@Test
public void copyRange() throws IOException {
InputStream inputStream = new FileSystemResource("D:\\a.txt").getInputStream();
OutputStream outputStream = new FileSystemResource("D:\\b.txt").getOutputStream();
//将给定 InputStream 的内容范围复制到给定 OutputStream。
// 如果指定范围超过 InputStream 的长度,则复制到流的末尾并返回实际复制的字节数。
// 完成后让两个流都打开。
long l = StreamUtils.copyRange(inputStream, outputStream, 0, 1);
System.err.println(l);//2
//关闭流
inputStream.close();
outputStream.close();
}
}
2.5.3 StreamUtils.copyToByteArray: 将给定 InputStream 的内容复制到一个新的字节数组中
byte[] copyToByteArray(@Nullable InputStream in)
将给定 InputStream 的内容复制到一个新的字节数组中.(完成后保持流打开)
in: 要从中复制的 InputStream
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: StreamUtils IO 流操作工具
*/
public class StreamUtilsTest {
// 将给定 InputStream 的内容复制到一个新的字节数组中
@Test
public void copyToByteArray() throws IOException {
InputStream inputStream = new FileSystemResource("D:\\a.txt").getInputStream();
byte[] bytes = StreamUtils.copyToByteArray(inputStream);
System.err.println(new String(bytes)); //--mhh
//关闭流
inputStream.close();
}
}
2.5.4 StreamUtils.copyToString: 将给定 InputStream 的内容复制到一个新的字符串中
String copyToString(@Nullable InputStream in, Charset charset)
将给定 InputStream 的内容复制到一个字符串中.(完成后保持流打开)
in: 要从中复制的 InputStream
charset: 字符集
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: StreamUtils IO 流操作工具
*/
public class StreamUtilsTest {
//将给定 InputStream 的内容复制到一个字符串中
@Test
public void copyToString() throws IOException {
InputStream inputStream = new FileSystemResource("D:\\a.txt").getInputStream();
System.err.println(StreamUtils.copyToString(inputStream, Charset.defaultCharset()));// copyToString --mhh
//关闭流
inputStream.close();
}
}
2.5.5 StreamUtils.drain: 排出给定 InputStream 的剩余内容
int drain(InputStream in)
将给定 InputStream 的内容复制到一个字符串中.(完成后保持流打开)
in: 要清空的 InputStream
return (int): 清空的字节数
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: StreamUtils IO 流操作工具
*/
public class StreamUtilsTest {
//清空流中数据
@Test
public void drain() throws IOException {
InputStream inputStream = new FileSystemResource("D:\\a.txt").getInputStream();
//清空流中数据,并返回清空个数
int drain = StreamUtils.drain(inputStream);
System.err.println(drain); //10
//打印流中数据个数
System.err.println(StreamUtils.copyToByteArray(inputStream).length);//0
//关闭流
inputStream.close();
}
}
2.6 ObjectUtils 对象、数组、集合操作工具
2.6.1 ObjectUtils.nullSafeClassName: 获取对象的类名
String nullSafeClassName(@Nullable Object obj) :
获取对象的类名。参数为 null 时,返回字符串:“null”
obj :要内省的对象
return :对应的类名
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 获取对象的类名。参数为 null 时,返回字符串:"null"
@Test
public void nullSafeClassName() {
//检验 null
System.err.println(ObjectUtils.nullSafeClassName(null));//"null"
//检验空字符串
System.err.println(ObjectUtils.nullSafeClassName(""));//java.lang.String
//检验字符串
System.err.println(ObjectUtils.nullSafeClassName("mhh"));//java.lang.String
//检验对象
System.err.println(ObjectUtils.nullSafeClassName(new Object()));//java.lang.Object
//检验数组
System.err.println(ObjectUtils.nullSafeClassName(new int[]{1, 2, 3}));//[I
//检验集合
System.err.println(ObjectUtils.nullSafeClassName(Arrays.asList("1", "2")));//java.util.Arrays$ArrayList
}
}
2.6.2 ObjectUtils.nullSafeHashCode: 获取对象的hashCode
int nullSafeHashCode(@Nullable Object obj) :
获取对象的hashCode 参数为 null 时,返回 0
obj : 获取hashCode的对象
return : hashCode值
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 获取对象的hashCode 参数为 null 时,返回 0
@Test
public void nullSafeHashCode() {
//检验null
String s = null;
System.err.println(ObjectUtils.nullSafeHashCode(s));//0
//检验空字符串
System.err.println(ObjectUtils.nullSafeHashCode(""));//0
//检验字符串
System.err.println(ObjectUtils.nullSafeHashCode("mhh"));//108077
//检验对象
System.err.println(ObjectUtils.nullSafeHashCode(new Object()));//1489069835
//检验数组
System.err.println(ObjectUtils.nullSafeHashCode(new int[]{1, 2, 3}));//209563
//检验集合
System.err.println(ObjectUtils.nullSafeHashCode(Arrays.asList("1", "2")));//2530
}
}
2.6.3 ObjectUtils.nullSafeToString: 返回指定对象的字符串表示形式
String nullSafeToString(@Nullable Object obj)
打印地址 toString方法 如果是 数组或集合则打印值 参数为 null 时,返回字符串:“null”
obj : 获取返回字符串形式的对象
return : 对象的字符串表示
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
//打印地址 toString方法 如果是 数组则打印值 参数为 null 时,返回字符串:"null"
// 与 getDisplayString(Object) 的不同之处在于对象是null时它返回一个"null",而不是 ""空字符串
@Test
public void nullSafeToString() {
//检验null
String s = null;
System.err.println(ObjectUtils.nullSafeToString(s));//"null"
//检验空字符串
System.err.println(ObjectUtils.nullSafeToString(""));//""
//检验字符串
System.err.println(ObjectUtils.nullSafeToString("mhh"));//mhh
//检验对象
System.err.println(ObjectUtils.nullSafeToString(new Object()));//java.lang.Object@58c1670b
//检验数组
System.err.println(ObjectUtils.nullSafeToString(new int[]{1, 2, 3}));//{1, 2, 3}
//检验集合
System.err.println(ObjectUtils.nullSafeToString(Arrays.asList("1", "2")));//[1, 2]
}
}
2.6.4 ObjectUtils.getIdentityHexString: 获取对象 HashCode(十六进制形式字符串)
String getIdentityHexString(Object obj)
获取对象 HashCode(十六进制形式字符串)。参数为 null 时,返回 0
obj : 入参对象
return : 对象的十六进制标识码
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
// 获取对象 HashCode(十六进制形式字符串)。参数为 null 时,返回 0
public void getIdentityHexString() {
//检验null
System.err.println(ObjectUtils.getIdentityHexString(null));//0
//检验空字符串
System.err.println(ObjectUtils.getIdentityHexString(""));//58c1670b
//检验字符串
System.err.println(ObjectUtils.getIdentityHexString("mhh"));//6b57696f
//检验对象
System.err.println(ObjectUtils.getIdentityHexString(new Object()));//6b57696f
//检验数组
System.err.println(ObjectUtils.getIdentityHexString(new int[]{1, 2, 3}));//5bb21b69
//检验集合
System.err.println(ObjectUtils.getIdentityHexString(Arrays.asList("1", "2")));//6b9651f3
}
}
2.6.5 ObjectUtils.identityToString: 获取对象的类名和 HashCode
String identityToString(@Nullable Object obj)
获取对象的类名和 HashCode。参数为 null 时,返回字符串:“”
obj : 入参对象
return : 对象的类名和hashCode
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 获取对象的类名和 HashCode。参数为 null 时,返回字符串:""
@Test
public void identityToString() {
//检验null
System.err.println(ObjectUtils.identityToString(null));//""
//检验空字符串
System.err.println(ObjectUtils.identityToString(""));//java.lang.String@58c1670b
//检验字符串
System.err.println(ObjectUtils.identityToString("mhh"));//java.lang.String@6b57696f
//检验对象
System.err.println(ObjectUtils.identityToString(new Object()));//java.lang.Object@6b57696f
//检验数组
System.err.println(ObjectUtils.identityToString(new int[]{1, 2, 3}));//[I@5bb21b69
//检验集合
System.err.println(ObjectUtils.identityToString(Arrays.asList("1", "2")));//java.util.Arrays$ArrayList@6b9651f3
}
}
2.6.6 ObjectUtils.identityToString: 打印地址 toString方法 如果是 数组或集合则打印值 参数为 null 时,返回字符串:""
String getDisplayString(@Nullable Object obj)
相当于 toString()方法,但参数为 null 时,返回字符串:“”
obj : 入参对象
return : 对象的字符串表示- 与 nullSafeToString(Object) 的不同之处在于它返回一个空字符串,而不是 {@code null} 值的“null”
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 相当于 toString()方法,但参数为 null 时,返回字符串:""
//与 nullSafeToString(Object) 的不同之处在于它返回一个空字符串,而不是 {@code null} 值的“null”
@Test
public void getDisplayString() {
//检验null
System.err.println(ObjectUtils.getDisplayString(null));//""
//检验空字符串
System.err.println(ObjectUtils.getDisplayString(""));//""
//检验字符串
System.err.println(ObjectUtils.getDisplayString("mhh"));//mhh
//检验对象
System.err.println(ObjectUtils.getDisplayString(new Object()));//java.lang.Object@6b57696f
//检验数组
System.err.println(ObjectUtils.getDisplayString(new int[]{1, 2, 3}));//{1, 2, 3}
//检验集合
System.err.println(ObjectUtils.getDisplayString(Arrays.asList("1", "2")));//[1, 2]
}
}
2.6.7 ObjectUtils.addObjectToArray: 将给定对象附加到给定数组
<A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj)
将给定对象附加到给定数组,返回一个由输入数组内容和给定对象组成的新数组
array : 要附加到的数组
obj : 要附加的对象
return : 新数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
//将给定对象附加到给定数组,返回一个由输入数组内容和给定对象组成的新数组
@Test
public void addObjectToArray() {
//注意必须是 Object类或子类
String[] i = {"1"};
String[] strings = ObjectUtils.addObjectToArray(i, "1");
System.err.println(Arrays.toString(i));//[1]
System.err.println(Arrays.toString(strings));//[1, 1]
}
}
2.6.8 ObjectUtils.caseInsensitiveValueOf: 忽略大小写获取指定的枚举对象
<E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant)
:忽略大小写获取指定的枚举对象,不存在则抛异常
enumValues : 枚举常量的数组
constant: 枚举值的常量
return : 枚举值
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 忽略大小写获取指定的枚举对象,不存在则抛异常
@Test
public void caseInsensitiveValueOf() {
AccessMode accessMode = ObjectUtils.caseInsensitiveValueOf(
new AccessMode[]{AccessMode.EXECUTE, AccessMode.WRITE, AccessMode.READ},//enumValues:所有有问题的枚举常量的数组,通常每个 {@code Enum.values()}
"read");//constant:获取枚举值的常量(忽略大小写)
System.err.println(accessMode);//READ
AccessMode exceptionAccessMode = ObjectUtils.caseInsensitiveValueOf(
new AccessMode[]{AccessMode.EXECUTE, AccessMode.WRITE, AccessMode.READ},
"aaa");//java.lang.IllegalArgumentException: Constant [aaa] does not exist in enum type java.nio.file.AccessMode
System.err.println(exceptionAccessMode);
}
}
2.6.9 ObjectUtils.containsConstant: 检查给定的枚举常量数组是否包含具有给定名称的常量
boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive)
:检查给定的枚举常量数组是否包含具有给定名称的常量(存在则为true,否则为false)
enumValues : 要检查的枚举值
constant: 要查找的常量名称
caseSensitive: 是否忽略大小写(默认为false 忽略大小写)
return : 是否在给定数组中找到常量
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
// 检查给定的枚举常量数组是否包含具有给定名称的常量
public void containsConstant() {
Boolean trueAccessMode = ObjectUtils.containsConstant(
new AccessMode[]{AccessMode.EXECUTE, AccessMode.WRITE, AccessMode.READ},//enumValues:要检查的枚举值,通常通过 {@code MyEnum.values()} 获得
"read", //constant:要查找的常量名称(不得为 null 或空字符串)
false);//caseSensitive:大小写在确定匹配时是否重要(默认false)
System.err.println(trueAccessMode);//true
Boolean falseAccessMode = ObjectUtils.containsConstant(
new AccessMode[]{AccessMode.EXECUTE, AccessMode.WRITE, AccessMode.READ},//enumValues:要检查的枚举值,通常通过 {@code MyEnum.values()} 获得
"read", //constant:要查找的常量名称(不得为 null 或空字符串)
true);//caseSensitive:大小写在确定匹配时是否重要(默认false)
System.err.println(falseAccessMode);//false
}
}
2.6.10 ObjectUtils.toObjectArray: 将给定数组(可能是原始数组)转换为对象数组(如果需要原始包装对象)
Object[] toObjectArray(@Nullable Object source)
:将给定数组(可能是原始数组)转换为对象数组 (如果需要原始包装对象),如果入参为null 源值将被转换为空的 Object 数组。
source: 入参数组
return : 对应的对象数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
//将给定数组(可能是原始数组)转换为对象数组(如果需要原始包装对象)。
// 如果入参为null 源值将被转换为空的 Object 数组。
public void toObjectArray() {
Object[] objects = ObjectUtils.toObjectArray(new int[]{123});
System.err.println(objects);//[Ljava.lang.Integer;@58c1670b
System.err.println(Arrays.toString(objects));//[123]
System.err.println(Arrays.toString(ObjectUtils.toObjectArray(null)));//[]
}
}
2.6.11 ObjectUtils.unwrapOptional: 解包Optional
Object unwrapOptional(@Nullable Object obj)
:解包给定的对象,如果不是Optional 则返回它本身
obj: 入参对象
return : 如果是 Optional 则返回 Optional中保存的值 Optional为空的话则返回null;如果不是Optional,则返回入参本身.
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
//解包给定的对象,它可能是一个 {@link java.util.Optional}。
//如果不是Optional 则返回它本身
public void unwrapOptional() {
String s = "123";
Object o = ObjectUtils.unwrapOptional(s);
System.err.println(o == s);//true
//创建Optional
Object optional = ObjectUtils.unwrapOptional(Optional.of("123"));
System.err.println(optional);//123
//创建空的 Opional
Object optionalEmpty = ObjectUtils.unwrapOptional(Optional.empty());
System.err.println(optionalEmpty);//null
}
}
2.6.12 ObjectUtils.isEmpty: 判断对象是否为空
boolean isEmpty(@Nullable Object[] array)
:判断给定数组是否为空:
array: 要检查的数组
return : 判断数组是否为null或者长度==0boolean isEmpty(@Nullable Object obj)
:判断给定对象是否为空:
obj: 要检查的对象
return : 判断对象是否为null如果是集合和Map 则还会判断是否有值)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
// 判断对象是否为空(空为true,否则为false)
@Test
public void isEmpty() {
//校验null
System.err.println(ObjectUtils.isEmpty(null));//true
//校验空字符串
System.err.println(ObjectUtils.isEmpty(""));//true
//校验字符串
System.err.println(ObjectUtils.isEmpty("mhh"));//false
//校验数组
System.err.println(ObjectUtils.isEmpty(new int[]{}));//true
System.err.println(ObjectUtils.isEmpty(new int[]{1,2}));//false
//校验集合
System.err.println(ObjectUtils.isEmpty(new ArrayList<>()));//true
System.err.println(ObjectUtils.isEmpty(Arrays.asList("1","2")));//false
//校验对象
System.err.println(ObjectUtils.isEmpty(new Object()));//false
}
}
2.6.13 ObjectUtils.isArray: 确定给定对象是否为数组
boolean isArray(@Nullable Object obj)
:确定给定对象是否为数组:对象数组或原始数组。(是数组则为true 否则为false)
obj: 要检查的对象
return : 是数组则为true 否则为false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
//确定给定对象是否为数组:对象数组或原始数组。(是数组则为true 否则为false)
@Test
public void isArray() {
Object[] objects=null;
System.err.println(ObjectUtils.isArray(objects));//false
System.err.println(ObjectUtils.isArray(new Object[]{}));//true
System.err.println(ObjectUtils.isArray(new int[]{}));//true
System.err.println(ObjectUtils.isArray(new ArrayList<>()));//false
System.err.println(ObjectUtils.isArray(new HashMap<>()));//false
System.err.println(ObjectUtils.isArray(new Object()));//false
}
}
2.6.14 ObjectUtils.containsElement: 判断给定数组是否包含给定元素
boolean containsElement(@Nullable Object[] array, Object element)
:判断给定数组是否包含给定元素。(包含则为true 否则为false)
array: 要检查的数组
element: 要检查的元素
return : 包含则为true 否则为false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
//检查给定数组是否包含给定元素。
public void containsElement() {
boolean integer = ObjectUtils.containsElement(
new Integer[]{1, 2, 3}, //array: 要检查的数组
3);//element: 要检查的元素
System.err.println(integer);//true
boolean string = ObjectUtils.containsElement(
new String[]{"A", "b", "c"}, //array: 要检查的数组
"a");//element: 要检查的元素
System.err.println(string);//false
}
}
2.6.15 ObjectUtils.nullSafeEquals: 确定给定对象是否相等;数组和集合基于元素比较
boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2)
:确定给定对象是否相等,如果两者都是 地址相等则返回 true;如果地址不等则返回 false;数组和集合基于元素比较而不是数组引用执行相等检查
o1: 第一个要比较的对象
o2: 第二个要比较的对象
return : 判断给定对象是否相等,如果是集合和数组则是比较内部元素。(相等返回true,否则为false)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.nio.file.AccessMode;
import java.util.*;
/**
* @创建人: Mhh
* @创建时间: 2022/4/8
* @描述: ObjectUtils常用方法
*/
@SpringBootTest
public class ObjectUtilsTest {
@Test
//确定给定对象是否相等,如果两者都是 地址相等则返回 true;如果地址不等则返回 false。
// 数组和集合基于元素比较而不是数组引用执行相等检查。
public void nullSafeEquals() {
Object o = new Object();
boolean trueObject = ObjectUtils.nullSafeEquals(o, o);
System.err.println(trueObject);//true
boolean falseObject = ObjectUtils.nullSafeEquals(new Object(), new Object());
System.err.println(falseObject);//false
boolean trueArray = ObjectUtils.nullSafeEquals(new String[]{"1", "2"}, new String[]{"1", "2"});
System.err.println(trueArray);//true
boolean falseArray = ObjectUtils.nullSafeEquals(new String[]{"1", "2"}, new String[]{"0", "2"});
System.err.println(falseArray);//false
boolean trueArrayList = ObjectUtils.nullSafeEquals(Arrays.asList(1, 2), Arrays.asList(1, 2));
System.err.println(trueArrayList);//true
boolean falseArrayList = ObjectUtils.nullSafeEquals(Arrays.asList(1, 2, 3), Arrays.asList(1, 2));
System.err.println(falseArrayList);//false
}
}
2.7 StringUtils 字符串操作工具
2.7.1 StringUtils.isEmpty: 判断字符串是否为 null,或 ""
boolean isEmpty(@Nullable Object str):
判断字符串是否为 null,或 “”。注意,包含空白符的字符串为非空
str:要检查的对象
return : 非空返回false 空或null返回true
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串是否为 null,或 ""。注意,包含空白符的字符串为非空
@Test
public void isEmpty() {
//校验null
System.err.println(StringUtils.isEmpty(null));//true
//校验空字符串
System.err.println(StringUtils.isEmpty(""));//true
//校验拥有空白符的字符串
System.err.println(StringUtils.isEmpty(" "));//false
}
}
2.7.2 StringUtils.hasLength: 判断字符串非空且长度不为 0,即,Not Empty
boolean hasLength(@Nullable String str):
判断字符串非空且长度不为 0,即,Not Empty
str: 要检查的对象
return: 非空返回true 空或null返回false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串非空且长度不为 0,即,Not Empty
@Test
public void hasLength() {
System.err.println(StringUtils.hasLength(null)); //false
System.err.println(StringUtils.hasLength("")); //false
System.err.println(StringUtils.hasLength(" ")); //true
System.err.println(StringUtils.hasLength("123")); //true
}
}
2.7.3 StringUtils.hasText: 判断字符串是否包含实际内容,即非仅包含空白符,也就是 Not Blank
boolean hasText(@Nullable String str):
判断字符串是否包含实际内容,即非仅包含空白符,也就是 Not Blank
str: 要检查的对象
return: 有实际值返回true, 空或null或空字符串返回false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串是否包含实际内容,即非仅包含空白符,也就是 Not Blank
@Test
public void hasText() {
System.err.println(StringUtils.hasText(null)); //false
System.err.println(StringUtils.hasText("")); //false
System.err.println(StringUtils.hasText(" ")); //false
System.err.println(StringUtils.hasText("123")); //true
}
}
2.7.4 StringUtils.endsWithIgnoreCase: 判断字符串是否是以指定内容结束。忽略大小写
boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix)
判断字符串是否是以指定内容结束。忽略大小写
str: 要检查的字符串
suffix: 要查找的后缀
return: 是则返回true, 不是则返回false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串是否是以指定内容结束。忽略大小写
@Test
public void endsWithIgnoreCase() {
System.err.println(StringUtils.endsWithIgnoreCase("abC", "C"));//true
System.err.println(StringUtils.endsWithIgnoreCase("abC", "c"));//true
System.err.println(StringUtils.endsWithIgnoreCase("123", "23"));//true
System.err.println(StringUtils.endsWithIgnoreCase("123", "3"));//true
System.err.println(StringUtils.endsWithIgnoreCase("123", "2"));//false
}
}
2.7.5 StringUtils.startsWithIgnoreCase: 判断字符串是否已指定内容开头。忽略大小写
boolean startsWithIgnoreCase(@Nullable String str, @Nullable String prefix)
: 判断字符串是否已指定内容开头。忽略大小写
str: 要检查的字符串
suffix: 要查找的前缀
return: 是则返回true, 不是则返回false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串是否已指定内容开头。忽略大小写
@Test
public void startsWithIgnoreCase() {
System.err.println(StringUtils.startsWithIgnoreCase("Abc", "ab"));//true
System.err.println(StringUtils.startsWithIgnoreCase("Abc", "a"));//true
System.err.println(StringUtils.startsWithIgnoreCase("Abc", "B"));//false
System.err.println(StringUtils.startsWithIgnoreCase("123", "1"));//true
System.err.println(StringUtils.startsWithIgnoreCase("123", "12"));//true
System.err.println(StringUtils.startsWithIgnoreCase("123", "3"));//false
}
}
2.7.6 StringUtils.containsWhitespace: 是否包含空白符
boolean containsWhitespace(@Nullable String str)
: 是否包含空白符(包含为true 否则为false)
str: 要检查的字符串
return: 包含空白符则是true,否则为false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 是否包含空白符(包含为true 否则为false)
@Test
public void containsWhitespace() {
System.err.println(StringUtils.containsWhitespace(null));// false
System.err.println(StringUtils.containsWhitespace(""));// false
System.err.println(StringUtils.containsWhitespace(" "));// true
System.err.println(StringUtils.containsWhitespace("abc"));// false
System.err.println(StringUtils.containsWhitespace("ab c"));// true
}
}
2.7.7 StringUtils.substringMatch: 判断字符串指定索引处是否包含一个指定子串
boolean substringMatch(CharSequence str, int index, CharSequence substring)
: 判断字符串指定索引处是否包含一个指定子串
str: 要检查的字符串
index: 要开始匹配的要检查字符串中的索引
substring: 在给定索引处匹配的子字符串
return: 如果在指定处包含给定的子字符串则是true,否则为false
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串指定索引处是否包含一个指定子串。
@Test
public void substringMatch() {
System.err.println(StringUtils.substringMatch("abc", 0, "a"));//true
System.err.println(StringUtils.substringMatch("abc", 1, "a"));//false
}
}
2.7.8 StringUtils.countOccurrencesOf: 计算一个字符串中指定子串的出现次数
int countOccurrencesOf(String str, String sub)
: 判断字符串指定索引处是否包含一个指定子串
str: 要检查的字符串
sub: 要搜索的字符串
return: 搜索的字符串出现的次数
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 判断字符串指定索引处是否包含一个指定子串。
@Test
public void substringMatch() {
// 计算一个字符串中指定子串的出现次数
@Test
public void countOccurrencesOf() {
System.err.println(StringUtils.countOccurrencesOf("aaab", "ab"));// 1
System.err.println(StringUtils.countOccurrencesOf("aaab", "a"));// 3
System.err.println(StringUtils.countOccurrencesOf("aaab", "b"));// 1
System.err.println(StringUtils.countOccurrencesOf("aaab", "c"));// 0
}
}
2.7.9 StringUtils.replace: 查找并替换指定子串
String replace(String inString, String oldPattern, @Nullable String newPattern)
: 查找并替换指定子串
inString: 要检查的字符串
oldPattern: 要替换的字符串
newPattern: 要插入的字符串
return: 替换完的字符串(如果没有替换的字符则返回的原地址,否则新地址)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 查找并替换指定子串
@Test
public void replace() {
//如果没有被替换 则返回的是原来的地址
String s = new String("abc123");
String replace = StringUtils.replace(s, null, null);
System.err.println(replace == s);//true
System.err.println(StringUtils.replace("abc123", "abc", "123"));//123123
System.err.println(StringUtils.replace("abc123", "456", "123"));//abc123
}
}
2.7.10 StringUtils.trimTrailingCharacter: 去除尾部的特定字符
String trimTrailingCharacter(String str, char trailingCharacter)
: 去除尾部的特定字符
str: 要检查的字符串
leadingCharacter: 要去除尾部的字符
return: 去除完成的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除尾部的特定字符
@Test
public void trimTrailingCharacter() {
System.err.println(StringUtils.trimTrailingCharacter("abc", 'c')); //ab
System.err.println(StringUtils.trimTrailingCharacter("abc", 'b')); //abc
System.err.println(StringUtils.trimTrailingCharacter("abc", '1')); //abc
}
}
2.7.11 StringUtils.trimLeadingCharacter: 去除头部的特定字符
String trimLeadingCharacter(String str, char leadingCharacter)
: 去除头部的特定字符
str: 要检查的字符串
leadingCharacter: 要去除头部的字符
return: 去除完成的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除头部的特定字符
@Test
public void trimLeadingCharacter() {
System.err.println(StringUtils.trimLeadingCharacter("abc", 'a')); //bc
System.err.println(StringUtils.trimLeadingCharacter("abc", 'b')); //abc
System.err.println(StringUtils.trimLeadingCharacter("abc", 'c')); //abc
System.err.println(StringUtils.trimLeadingCharacter("abc", '1')); //abc
}
}
2.7.12 StringUtils.trimLeadingWhitespace: 去除头部的空白符
String trimLeadingWhitespace(String str)
: 去除头部的空白符
str: 要检查的字符串
return: 去除完头部空白的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除头部的空白符
@Test
public void trimLeadingWhitespace() {
System.err.println(StringUtils.trimLeadingWhitespace(null)); //null
System.err.println(StringUtils.trimLeadingWhitespace("12")); //"12"
System.err.println(StringUtils.trimLeadingWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimLeadingWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimLeadingWhitespace("1 2")); //"1 2"
System.err.println(StringUtils.trimLeadingWhitespace("12 ")); //"12 "
}
}
2.7.13 StringUtils.trimTrailingWhitespace: 去除尾部的空白符
String trimTrailingWhitespace(String str)
: 去除尾部的空白符
str: 要检查的字符串
return: 去除完尾部空白的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除尾部的空白符
@Test
public void trimTrailingWhitespace() {
System.err.println(StringUtils.trimTrailingWhitespace(null)); //null
System.err.println(StringUtils.trimTrailingWhitespace("12")); //"12"
System.err.println(StringUtils.trimTrailingWhitespace(" 12")); //" 12"
System.err.println(StringUtils.trimTrailingWhitespace(" 12")); //" 12"
System.err.println(StringUtils.trimTrailingWhitespace("1 2")); //"1 2"
System.err.println(StringUtils.trimTrailingWhitespace("12 ")); //"12"
System.err.println(StringUtils.trimTrailingWhitespace("12 ")); //"12"
}
}
2.7.14 StringUtils.trimWhitespace: 去除头部和尾部的空白符
String trimWhitespace(String str)
: 去除头部和尾部的空白符
str: 要检查的字符串
return: 去除完尾部和头部空白的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除头部和尾部的空白符
@Test
public void trimWhitespace() {
System.err.println(StringUtils.trimWhitespace(null)); //null
System.err.println(StringUtils.trimWhitespace("12")); //"12"
System.err.println(StringUtils.trimWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimTrailingWhitespace("1 2")); //"1 2"
System.err.println(StringUtils.trimTrailingWhitespace("12 ")); //"12"
System.err.println(StringUtils.trimTrailingWhitespace("12 ")); //"12"
}
}
2.7.15 StringUtils.trimAllWhitespace: 去除字符串中所有的空白符
String trimAllWhitespace(String str)
: 去除头部和中间和尾部的空白符
str: 要检查的字符串
return: 去除完所有空白符的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 去除头部和中间和尾部的空白符
@Test
public void trimAllWhitespace() {
System.err.println(StringUtils.trimAllWhitespace(null)); //null
System.err.println(StringUtils.trimAllWhitespace("12")); //"12"
System.err.println(StringUtils.trimAllWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimAllWhitespace(" 12")); //"12"
System.err.println(StringUtils.trimAllWhitespace("1 2")); //"12"
System.err.println(StringUtils.trimAllWhitespace("1 2")); //"12"
System.err.println(StringUtils.trimAllWhitespace("12 ")); //"12"
System.err.println(StringUtils.trimAllWhitespace("12 ")); //"12"
}
}
2.7.16 StringUtils.delete: 删除所有出现的给定子字符串
String delete(String inString, String pattern)
: 删除所有出现的给定子字符串
inString: 要检查的字符串
pattern: 要删除的字符串
return: 去除完所有要删除的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 删除所有出现的给定子字符串。
@Test
public void delete() {
System.err.println(StringUtils.delete("abc123", "b")); // ac123
System.err.println(StringUtils.delete("abc123", "a")); // bc123
System.err.println(StringUtils.delete("abc123", "a1")); // abc123
System.err.println(StringUtils.delete("abc123", "ac123")); // abc123
}
}
2.7.17 StringUtils.deleteAny: 删除给定字符串中的任何字符
String deleteAny(String inString, @Nullable String charsToDelete)
: 删除给定 {@code String} 中的任何字符。
inString: 要检查的字符串
charsToDelete: 一组要删除的字符
return: 去除完所有要删除字符的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//删除给定 {@code String} 中的任何字符。
@Test
public void deleteAny() {
System.err.println(StringUtils.deleteAny("abc123", "ab")); // c123
System.err.println(StringUtils.deleteAny("abc123", "a")); // bc123
System.err.println(StringUtils.deleteAny("abc123", "a1")); // bc23
System.err.println(StringUtils.deleteAny("abc123", "c2a31")); // b
}
}
2.7.18 StringUtils.trimArrayElements: 对数组的每一项执行 trim() 方法(删除前端和尾端的空白字符)
String[] trimArrayElements(String[] array)
: 对数组的每一项执行 trim() 方法(删除前端和尾端的空白字符)。
array: 要检查的字符串
return: 去除完前端和后端的空白字符的字符串数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 对数组的每一项执行 trim() 方法(删除前端和尾端的空白字符)
@Test
public void trimArrayElements() {
System.err.println(Arrays.toString(StringUtils.
trimArrayElements(new String[]{" 12", "1 2", "12 ", " 1 2 "}))); //[12, 1 2, 12, 1 2]
}
}
2.7.19 StringUtils.addStringToArray: 将给定的字符串附加到给定的字符串数组中
String[] addStringToArray(@Nullable String[] array, String str)
: 将给定的字符串附加到给定的字符串数组中,返回一个新数组。
array: 要附加到的数组
str: 要附加的字符串
return: 附加完字符串的新数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 将给定的 {@code String} 附加到给定的 {@code String} 数组中,返回一个由输入数组内容加上给定的 {@code String} 组成的新数组。
@Test
public void addStringToArray() {
System.err.println(Arrays.toString(StringUtils.
addStringToArray(new String[]{"1", "2"}, "3")));//[1, 2, 3]
}
}
2.7.20 StringUtils.arrayToCommaDelimitedString: 将入参数组转换为逗号分隔的字符串返回
String arrayToCommaDelimitedString(@Nullable Object[] arr)
: 将入参数组转换为逗号分隔的字符串返回
array: 指定的数组
return: 指定的数组用 ‘,’ 分割后的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//将入参数组转换为逗号分隔的字符串返回
@Test
public void arrayToCommaDelimitedString() {
System.err.println(StringUtils.arrayToCommaDelimitedString(new Object[]{new Object(), "2", 3})); //java.lang.Object@23d2a7e8,2,3
System.err.println(StringUtils.arrayToCommaDelimitedString(new String[]{"1", "2", "3"})); //1,2,3
System.err.println(StringUtils.arrayToCommaDelimitedString(new Integer[]{1, 2, 3, 4})); //1,2,3,4
}
}
2.7.21 StringUtils.arrayToDelimitedString: 将入参数组转换为指定分隔符进行分隔 并转为字符串返回
String arrayToDelimitedString(@Nullable Object[] arr, String delim)
: 将入参数组转换为指定分隔符进行分隔 并转为字符串返回
array: 指定的数组
delim: 指定的分隔符
return: 指定的数组用 指定的分隔符 分割后的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//将入参数组转换为指定分隔符进行分隔 并转为字符串返回
@Test
public void arrayToDelimitedString() {
System.err.println(StringUtils.
arrayToDelimitedString(new String[]{"1", "2", "3"}, "-")); // 1-2-3
System.err.println(StringUtils.
arrayToDelimitedString(new Integer[]{1, 2, 3, 4}, "|")); // 1|2|3|4
}
}
2.7.22 StringUtils.collectionToCommaDelimitedString: 将入参集合转换为逗号分隔符进行分隔 并转为字符串返回
String collectionToCommaDelimitedString(@Nullable Collection<?> coll)
: 将入参集合转换为逗号分隔符进行分隔 并转为字符串返回
coll: 指定的集合
return: 指定的集合内数据用逗号分割后的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//将入参集合转换为逗号分隔符进行分隔 并转为字符串返回
@Test
public void collectionToCommaDelimitedString() {
System.err.println(StringUtils.
collectionToCommaDelimitedString(Arrays.asList("1", "2", "3"))); //1,2,3
}
}
2.7.23 StringUtils.collectionToCommaDelimitedString: 将入参集合转换为指定分隔符进行分隔 并转为字符串返回
String collectionToDelimitedString(@Nullable Collection<?> coll, String delim)
: 将入参集合转换为指定分隔符进行分隔 并转为字符串返回
coll: 指定的集合
delim: 指定的分隔符
return: 指定的集合用 指定的分隔符 分割后的字符串String collectionToDelimitedString( @Nullable Collection<?> coll, String delim, String prefix, String suffix)
:将入参集合转换为指定分隔符进行分隔 并转为字符串返回(并可以在元素之前和之后插入数据)
coll: 指定的集合
delim: 指定的分隔符
prefix: 元素之前需添加的字符串
suffix: 元素之后需添加的字符串
return: 返回分割后的字符串
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 将入参集合转换为指定分隔符进行分隔 并转为字符串返回
@Test
public void collectionToDelimitedString() {
System.err.println(StringUtils.
collectionToDelimitedString(
Arrays.asList("1", "2", "3"), "|"));// 1|2|3
System.err.println(StringUtils.
collectionToDelimitedString(
Arrays.asList("1", "2"), "|", "a", "b"));// a1b|a2b
}
}
2.7.24 StringUtils.capitalize: 将第一个字母更改为大写
String capitalize(String str)
: 将第一个字母更改为大写。其他字母没有变化
str: 指定的字符串
return: 如果第一个是字母的话,就返回第一个字母大写的字符串;否则参数不变返回
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//将第一个字母更改为大写。其他字母没有变化
@Test
public void capitalize() {
System.err.println(StringUtils.capitalize("abc"));//Abc
System.err.println(StringUtils.capitalize("孟abc"));//孟abc
System.err.println(StringUtils.capitalize("123"));//123
}
}
2.7.25 StringUtils.uncapitalize: 取消大写 将第一个字母更改为小写。其他字母没有变化
String uncapitalize(String str)
: 取消大写 将第一个字母更改为小写。其他字母没有变化
str: 指定的字符串
return: 如果第一个是大写字母的话,就取消大写其它的不变
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//取消大写 将第一个字母更改为小写。其他字母没有变化
@Test
public void uncapitalize() {
System.err.println(StringUtils.uncapitalize("ABc"));//aBc
System.err.println(StringUtils.uncapitalize("孟Abc"));//孟Abc
System.err.println(StringUtils.uncapitalize("123"));//123
}
}
2.7.26 StringUtils.getFilenameOrgetFilenameExtension: 规范化路径 OR 获取路径上的附件名 OR 文件扩展名
String cleanPath(String path)
: 进行规范化 将 “\“转为”/”
path: 指定的字符串路径
return: 规范化路径String getFilename(@Nullable String path)
: 获取附件名
path: 指定的字符串路径
return: 附件名String getFilenameExtension(@Nullable String path)
: 获取后缀扩展名
path: 指定的字符串路径
return: 后缀扩展名
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//获取路径上的附件名OR文件扩展名
@Test
public void getFilenameOrgetFilenameExtension() {
// 进行规范化 将 "\\"转为"/"
String cleanPath = StringUtils.cleanPath("C:\\Mhh\\HP\\Desktop\\eureka\\start.bat.txt");
System.err.println(cleanPath);// C:/Mhh/HP/Desktop/eureka/start.bat.txt
//获取附件名
System.err.println(StringUtils.getFilename(cleanPath));// start.bat.txt
//获取后缀
System.err.println(StringUtils.getFilenameExtension(cleanPath));// txt
}
}
2.7.27 StringUtils.pathEquals: 在对它们进行cleanPath(规范化)后比较两条路径
boolean pathEquals(String path1, String path2)
: 在对它们进行cleanPath(规范化)后比较两条路径
path1: 第一个比较路径
path2: 第二个比较路径
return: 返回比较结果
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//在对它们进行cleanPath(规范化)后比较两条路径。
@Test
public void pathEquals() {
System.err.println(StringUtils.
pathEquals("C:/Mhh/HP/Desktop/eureka/start.bat",
"C:\\Mhh\\HP\\Desktop\\eureka\\start.bat"));//true
}
}
2.7.28 StringUtils.parseTimeZoneString: 获取 TimeZone时区
TimeZone parseTimeZoneString(String timeZoneString)
: 获取 TimeZone时区
timeZoneString: 时间区域
return: 返回时区对象TimeZone
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//获取 TimeZone时区
@Test
public void parseTimeZoneString() {
// 获取 “GMT+08:00”对应的时区
System.err.println(StringUtils.parseTimeZoneString("GMT+:08:00"));
}
}
2.7.29 StringUtils.quote: 用单引号引用给定的值
String quote(@Nullable String str)
: 用单引号引用给定的值
str: 指定的字符串
return: 被单引号引起来的参数
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//用单引号引用给定的值
@Test
public void quote() {
System.err.println(StringUtils.quote(null));// null
System.err.println(StringUtils.quote(""));// ''
System.err.println(StringUtils.quote(" "));// ' '
System.err.println(StringUtils.quote("mhh"));// 'mhh'
}
}
2.7.30 StringUtils.removeDuplicateStrings: 从给定的数组中删除重复的字符串
String[] removeDuplicateStrings(String[] array)
: 从给定的数组中删除重复的字符串
array: 指定的字符串数组
return: 删除掉重复字符串的数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//从给定的数组中删除重复的字符串
@Test
public void removeDuplicateStrings() {
System.err.println(Arrays.
toString(StringUtils.
removeDuplicateStrings(
new String[]{"1", "1", "2", "2"})));//[1, 2]
}
}
2.7.31 StringUtils.sortStringArray: 如有必要,对给定的 入参数组进行排序(升序)。
String[] sortStringArray(String[] array)
: 如有必要,对给定的 入参数组进行排序(升序)。
array: 指定的字符串数组
return: 升序排序的字符串的数组
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
// 如有必要,对给定的 入参数组进行排序(升序)。
@Test
public void sortStringArray() {
System.err.println(Arrays.
toString(StringUtils.
sortStringArray(
new String[]{"7", "6", "2"})));//[2, 6, 7]
System.err.println(Arrays.
toString(StringUtils.
sortStringArray(
new String[]{"v", "d", "a"})));//[a, d, v]
//可以尝试 实现Comparable接口制定排序规则
System.err.println(Arrays.
toString(StringUtils.
sortStringArray(
new String[]{"孟", "张", "陈"})));//[孟, 张, 陈]
}
}
2.7.32 StringUtils.split: 在指定分隔符的第一次出现处拆分,结果中不包含分隔符。(只拆分一次)
String[] split(@Nullable String toSplit, @Nullable String delimiter)
: 在指定分隔符的第一次出现处拆分,结果中不包含分隔符。(只拆分一次)
toSplit: 要拆分的字符串
delimiter: 指定的拆分符
return: 拆分后的结果(只拆分一次)
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//在分隔符的第一次出现处拆分 {@code String}。结果中不包含分隔符。(只拆分一次)
@Test
public void split() {
System.err.println(
Arrays.toString("a.b.c".split("\\.")));//[a, b, c]
System.err.println(Arrays.toString(
StringUtils.split("a.b.c", "."))); //[a, b.c]
}
}
2.7.33 StringUtils.unqualify: 获取入参制定分隔符最后的一部分
String unqualify(String qualifiedName, char separator)
: 获取入参制定分隔符最后的一部分
qualifiedName: 要拆分的字符串
delimiter: 指定的拆分符
return: 获取分隔符的最后一部分
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/13
* @描述: 字符串工具
*/
@SpringBootTest
public class StringUtilsTest {
//获取入参制定分隔符最后的一部分
@Test
public void unqualify() {
System.err.println(StringUtils.
unqualify("a.b.c", '.'));//c
System.err.println(StringUtils.
unqualify("C:\\Mhh\\HP\\start.bat", '\\'));//start.bat
}
}
2.8 ReflectionUtils 反射、AOP操作工具
2.8.1 ReflectionUtils.findMethod: 在类中查找指定方法
Method findMethod(Class<?> clazz, String name):
在类中查找不带入参的指定方法
clazz:内省的类对象
name:方法的名称
return : 返回指定的方法,如果没有则是nullMethod findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes):
在类中查找携带入参的指定方法
clazz:内省的类对象
name:方法的名称
paramTypes…:方法的入参 参数类型
return : 返回指定的方法,如果没有则是null
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 在类中查找指定方法
@Test
public void findMethod() throws InvocationTargetException, IllegalAccessException {
在类中查找指定方法
Method trim = ReflectionUtils.findMethod(String.class, "trim");
System.err.println(trim.invoke(" abc"));//abc
// clazz:内省的类
// name: 内省的方法
// paramTypes...: 方法的入参 参数类型
Method trim1 = ReflectionUtils.findMethod(String.class, "trim", String.class);
System.err.println(trim1);//null
}
}
2.8.2 ReflectionUtils.getAllDeclaredMethods: 获得类中所有方法,包括继承而来的
Method[] getAllDeclaredMethods(Class<?> leafClass)
获得类中所有方法,包括继承而来的
leafClass:内省的类对象
return : 这个类中所有的方法(包括继承而来的)
- Student JavaBean
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 获得类中所有方法,包括继承而来的
@Test
public void getAllDeclaredMethods() {
System.err.println(Arrays.toString(ReflectionUtils.getAllDeclaredMethods(Student.class)));
//[
// public java.lang.String com.it.mhh.entity.Student.getName(),
// public void com.it.mhh.entity.Student.setName(java.lang.String),
// public void java.util.ArrayList.add(int,java.lang.Object),
// public boolean java.util.ArrayList.add(java.lang.Object)
// .....]
}
}
2.8.3 ReflectionUtils.getDeclaredMethods: 获得类中所有方法,不包括继承而来的
Method[] getDeclaredMethods(Class<?> clazz)
获得类中所有方法,不包括继承而来的
clazz:内省的类对象
return : 这个类中所有的方法(不包括继承而来的)
- Student JavaBean
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 获得类中所有方法,不包括继承而来的
@Test
public void getDeclaredMethods() {
System.err.println(Arrays.toString(ReflectionUtils.getDeclaredMethods(Student.class)));
// [
//public java.lang.String com.it.mhh.entity.Student.toString(),
// public java.lang.String com.it.mhh.entity.Student.getName(),
// public void com.it.mhh.entity.Student.setName(java.lang.String)
// ]
}
}
2.8.4 ReflectionUtils.accessibleConstructor: 在类中查找指定构造方法
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
在类中查找指定构造方法
clazz:内省的类对象
parameterTypes:所需构造函数入参的参数类型
return : 这个类中的构造方法
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 在类中查找指定构造方法
@Test
public void accessibleConstructor() throws NoSuchMethodException {
// clazz:要检查的 Class
// parameterTypes... : 所需构造函数的参数类型
System.err.println(ReflectionUtils.accessibleConstructor(String.class));//public java.lang.String()
// clazz:要检查的 Class
// parameterTypes... : 所需构造函数的参数类型
System.err.println(ReflectionUtils.accessibleConstructor(String.class, String.class));//public java.lang.String(java.lang.String)
}
}
2.8.5 ReflectionUtils.declaresException: 检查一个方法是否声明抛出指定异常
boolean declaresException(Method method, Class<?> exceptionType)
:检查一个方法是否声明抛出指定异常
method:声明方法
exceptionType:抛出的异常
return : 指定方法是否抛出指定异常
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 检查一个方法是否声明抛出指定异常
@Test
public void declaresException() {
//获取名为getBytes 入参为String类型的方法
Method method = ReflectionUtils.findMethod(String.class, "getBytes", String.class);
// 检查一个方法是否声明抛出指定异常
System.err.println(ReflectionUtils.
declaresException(method, UnsupportedEncodingException.class));//true
System.err.println(ReflectionUtils.
declaresException(method, Exception.class));//false
}
}
2.8.6 ReflectionUtils.invokeMethod: 执行方法
Object invokeMethod(Method method, @Nullable Object target, @Nullable Object... args)
:执行方法
method:调用的方法
target:调用方法的目标对象
args…:调用参数
return : 指定方法执行结果
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 执行方法
@Test
public void invokeMethod() {
//获取名为getBytes 入参为Charset类型的方法
// clazz: 反射类
// name: 反射类中方法的名称
// paramTypes...: 方法的入参 参数类型
Method method = ReflectionUtils.findMethod(String.class, "getBytes", Charset.class);
// 执行方法
// method:调用的方法
// target: 调用方法的目标对象
// args:调用方法的入参 参数
System.err.println(ReflectionUtils.invokeMethod(method, "Abc", StandardCharsets.UTF_8));//[B@543788f3
}
}
2.8.7 ReflectionUtils.makeAccessible: 取消 Java 权限检查。后续执行私有方法
void makeAccessible(Method method)
:取消 Java 权限检查。后续执行私有方法
method:调用的方法
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
//取消 Java 权限检查。后续执行私有方法
@Test
public void makeAccessible() {
//获取名为readResolve 没有入参的方法
// clazz: 反射类
// name: 反射类中方法的名称
// paramTypes...: 方法的入参 参数类型
Method method = ReflectionUtils.findMethod(String.class, "indexOfSupplementary", int.class, int.class);
// 取消 Java 权限检查。以便后续执行该私有方法
ReflectionUtils.makeAccessible(method);
// 执行方法
// method:调用的方法
// target: 调用方法的目标对象
// args:调用方法的入参 参数
System.err.println(ReflectionUtils.invokeMethod(method, "Abc", 1, 1));// -1
}
}
2.8.8 ReflectionUtils.findField: 在类中查找指定属性
Field findField(Class<?> clazz, @Nullable String name, @Nullable Class<?> type)
:在类中查找指定属性
clazz:内省的对象
name:字段的名称
type:字段的类型
return : 对应的 Field 对象,如果没有则是null
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 执行方法
@Test
public void invokeMethod() {
// 在类中查找指定属性
@Test
public void findField() throws IllegalAccessException {
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field field = ReflectionUtils.findField(String.class, "hash", int.class);
//权限为私的 解除!
field.setAccessible(true);
//获取属性值(入参为 要获取此值的对象)
System.err.println(field.get("abc"));//0 {缓存字符串的哈希码:默认为0}
}
}
2.8.9 ReflectionUtils.isPublicStaticFinal: 是否为一个 "public static final" 属性
boolean isPublicStaticFinal(Field field)
:是否为一个 “public static final” 属性
field: 要检查的字段
return : 如果此字段是一个 “public static final” 属性则返回true 否则为false
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 是否为一个 "public static final" 属性
@Test
public void isPublicStaticFinal() {
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field hashField = ReflectionUtils.findField(String.class, "hash", int.class);
// 是否为一个 "public static final" 属性
System.err.println(ReflectionUtils.isPublicStaticFinal(hashField));// false
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field MIN_VALUE_Filed = ReflectionUtils.findField(Integer.class, "MIN_VALUE", int.class);
// 是否为一个 "public static final" 属性
System.err.println(ReflectionUtils.isPublicStaticFinal(MIN_VALUE_Filed));// true
}
}
2.8.10 ReflectionUtils.getField: 获取传入对象的指定字段值
Object getField(Field field, @Nullable Object target)
:获取传入对象的指定字段值
field: 指定的字段
target: 从中获取字段的目标对象
return : 返回指定字段的字段值
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 获取传入对象的指定属性值
@Test
public void getField() {
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field hashField = ReflectionUtils.findField(String.class, "hash", int.class);
//因为此属性是私有的,所以需要解除私有权限
ReflectionUtils.makeAccessible(hashField);
//执行,获取传入对象的指定属性值
System.err.println(ReflectionUtils.getField(hashField, "abc"));//0 {缓存字符串的哈希码:默认为0}
}
}
2.8.11 ReflectionUtils.setField: 设置 传入对象的 指定 字段值
void setField(Field field, @Nullable Object target, @Nullable Object value)
:设置 传入对象的 指定 字段值
field: 要设置的字段
target: 设置字段的目标对象
value: 要设置的值
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 设置 传入对象的 指定 属性值
@Test
public void setField() {
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field hashField = ReflectionUtils.findField(String.class, "hash", int.class);
//因为此属性是私有的,所以需要解除私有权限
ReflectionUtils.makeAccessible(hashField);
String s = "";
// 设置 传入对象的 指定 属性值
ReflectionUtils.setField(hashField, s, 123);
// 获取 传入对象的 指定 属性值
System.err.println(ReflectionUtils.getField(hashField, s));//123
}
}
2.8.12 ReflectionUtils.shallowCopyFieldState: 同类对象属性对等赋值
void shallowCopyFieldState(final Object src, final Object dest)
:同类对象属性对等赋值
src: 源对象
dest: 目标对象
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 同类对象属性对等赋值
@Test
public void shallowCopyFieldState() {
//测试对象1
String src = "start";
//测试对象2
String dest = "end";
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field hashField = ReflectionUtils.findField(String.class, "hash", int.class);
//因为此属性是私有的,所以需要解除私有权限
ReflectionUtils.makeAccessible(hashField);
// 设置 传入对象的 指定 属性值
ReflectionUtils.setField(hashField, src, 123);
// 同类对象属性对等赋值
ReflectionUtils.shallowCopyFieldState(src, dest);
//获取 传入对象的 指定 属性值
System.err.println(ReflectionUtils.getField(hashField, dest));//123
}
}
2.8.13 ReflectionUtils.doWithFields: 对指定类的每个字段执行前 回调doWith(包括继承而来的字段)
void doWithFields(Class<?> clazz, FieldCallback fc, @Nullable FieldFilter ff)
:对指定类的每个属性执行前 回调doWith(包括继承而来的属性)
clazz: 要分析的目标类
fc: 为每个字段调用的回调
ff: 确定要应用回调的字段的过滤器
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 对指定类的每个属性执行前 回调doWith(包括继承而来的属性)
@Test
public void doWithFields() throws IllegalAccessException {
//测试字符串
String test = "";
//回调方法
// clazz:指定哪个类执行回调
ReflectionUtils.doWithFields(String.class, new ReflectionUtils.FieldCallback() {
//回调执行方法体
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
//私有属性限制解除
field.setAccessible(true);
//设定指定对象的此属性值
field.set(test, 123);
//打印下属性名
System.err.println(field.getName());//hash
}
}, new ReflectionUtils.FieldFilter() {
//确定要应用回调的字段的过滤器(没有填这个过滤器表示所有字段都会执行回调)
@Override
public boolean matches(Field field) {
//只有属性为hash的走过滤器
return field.getName().equals("hash");
}
});
// 在类中查找指定属性
// clazz: 反射类
// name: 反射类中属性的名称
// type: 属性的类型
Field hashField = ReflectionUtils.findField(String.class, "hash", int.class);
//私有属性限制解除
hashField.setAccessible(true);
//打印指定对象的属性值
System.err.println(hashField.get(test));//123
}
}
2.8.14 ReflectionUtils.doWithLocalFields: 对指定类的每个字段执行前 回调doWith(不包含继承而来的字段)
void doWithLocalFields(Class<?> clazz, FieldCallback fc)
:对指定类的每个属性执行前 回调doWith(不包括继承而来的属性)
clazz: 要分析的目标类
fc: 为每个字段调用的回调
- Student JavaBean
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 对指定类的每个属性执行前 回调doWith(不包含继承而来的属性)
@Test
public void doWithLocalFields() {
//-----------------------------对指定类的每个属性执行前 回调doWith-----------------------------------
//回调方法
// clazz:指定哪个类执行回调
ReflectionUtils.doWithFields(Student.class, new ReflectionUtils.FieldCallback() {
//回调执行方法体
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
//打印下属性名
System.err.println(field.getName() + "-----");//
/*
name-----
serialVersionUID-----
DEFAULT_CAPACITY-----
EMPTY_ELEMENTDATA-----
DEFAULTCAPACITY_EMPTY_ELEMENTDATA-----
......
*/
}
});
//--------------------------对指定类的每个属性执行前 回调doWith(但不包括继承而来的属性)-------------------------------------
//回调方法
// clazz:指定哪个类执行回调
ReflectionUtils.doWithLocalFields(Student.class, new ReflectionUtils.FieldCallback() {
//回调执行方法体
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
//打印下属性名
System.err.println(field.getName());
/*
name
*/
}
});
}
}
2.8.15 ReflectionUtils.doWithMethods: 对指定类的每个方法执行前 回调doWith(包括继承而来的方法)
void doWithMethods(Class<?> clazz, MethodCallback mc, @Nullable MethodFilter mf)
:对指定类的每个方法执行前 回调doWith(包括继承而来的方法)
clazz: 要分析的目标类
mc: 为每个方法调用的回调
mf: 确定将回调应用到的方法的过滤器
//import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 对指定类的每个方法执行前 回调doWith(包括继承而来的方法)
@Test
public void doWithMethods() {
//回调方法
// clazz:指定哪个类执行回调
ReflectionUtils.doWithMethods(String.class, new ReflectionUtils.MethodCallback() {
//回调执行方法体
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
System.err.println(method.getName());
}
}, new ReflectionUtils.MethodFilter() {
//确定要应用回调方法的过滤器(没有填这个过滤器表示所有方法都会执行回调)
@Override
public boolean matches(Method method) {
return method.getName().intern() == "equals";
}
});
}
}
2.8.16 ReflectionUtils.doWithLocalMethods: 对指定类的每个方法执行前 回调doWith(不包括继承而来的方法)
void doWithLocalMethods(Class<?> clazz, MethodCallback mc)
:对指定类的每个方法执行前 回调doWith(不包括继承而来的方法)
clazz: 要分析的目标类
mc: 为每个方法调用的回调
- Student JavaBean
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 对指定类的每个方法执行前 回调doWith(不包括继承而来的方法)
@Test
public void doWithLocalMethods(){
ReflectionUtils.doWithMethods(Student.class, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
System.err.println(method.getName()+"----");
/*
* getName----
setName----
add----
add----
remove----
remove----
* */
}
});
//
ReflectionUtils.doWithLocalMethods(Student.class, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
System.err.println(method.getName());
/*
* getName
* setName
* */
}
});
}
}
2.8.17 ReflectionUtils.getUniqueDeclaredMethods: 对象之间的copy 复制所有字段,包括继承的字段
void shallowCopyFieldState(final Object src, final Object dest)
:对象之间的copy 复制所有字段,包括继承的字段
src: 源对象
dest: 指定对象
- Student JavaBean
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
//对象之间的copy 复制所有字段,包括继承的字段
@Test
public void getUniqueDeclaredMethods(){
Student src = new Student();
src.setName("mhh");
Student dest = new Student();
ReflectionUtils.shallowCopyFieldState(src,dest);
System.err.println(dest);//Student{name='mhh'}
}
}
2.8.18 ReflectionUtils.clearCache: 清空缓存,每次查询(方法,参数)时都会做缓存
void clearCache()
:清空缓存,每次查询(方法,参数)时都会做缓存
import com.it.mhh.entity.Student;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @创建人: Mhh
* @创建时间: 2022/4/15
* @描述: 反射、AOP操作工具
*/
public class ReflectionUtilsTest {
// 清空缓存,每次查询(方法,参数)时都会做缓存。
@Test
public void clearCache(){
//清除缓存
ReflectionUtils.clearCache();
}
}