目录

Assert 断言工具类

ObjectUtils 对象工具类

Base64Utils Base64 编解码工具类

DigestUtils 摘要工具类

StringUtils 字符串工具类

FileSystemUtils 文件系统工具类

CollectionUtils 集合工具类

SerializationUtils 序列化工具类

StopWatch 秒表 

BeanUtils 内审与反射工具类

属性复制流行库对比

URI 编解码工具类 UriUtils 

请求参数工具类 ServletRequestUtils

FileCopyUtils 文件复制

ReflectionUtils 反射工具类

ResourceUtils 资源文件工具类

StreamUtils 流工具类

LinkedCaseInsensitiveMap 不区分大小 key

Resource 资源描述符


1、现在的 Java 开发基本离不开 springframework,而其中 spring-core-x.x.x.RELEASE.jar 核心包下提供了很多实用的工具类,开发中可以直接使用,没必要再自己重复的造轮子。

2、个人觉得 org.springframework.util 包下面的工具类与 apache 提供的工具类虽然大部分相差无几,但还是有互补的地方,开发中基本能满足常用的工具类使用。

3、导入 spring-boot-starter-web 依赖后就已经包含了 org.springframework.spring-web 包。

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Assert 断言工具类

1、org.springframework.util.Assert专门用于校验参数是否合法,不合法时抛出 "IllegalArgumentException-非法参数异常"

//比如断言参数不能为 null,Assert 源码如下:
public static void isNull(@Nullable Object object, String message) {
    if (object != null) {
        throw new IllegalArgumentException(message);
    }
}

2、Assert 中提供了常用的参数校验,从方法名字就能一目了然,汇总如下:

方法

描述

doesNotContain(@Nullable String textToSearch, String substring, String message)

1、断言给定的文本(textToSearch)不包含给定的子字符串(substring),

2、如果 textToSearch 包含子字符串(substring),则抛异常 IllegalArgumentException

3、message:断言失败时要使用的异常消息

hasLength(@Nullable String text, String message)

1、断言给定的字符串不是空的,空格不算作空,

2、如果文本为空,或者为 null,则抛出 IllegalArgumentException

hasText(@Nullable String text, String message)

1、断言给定的字符串包含有效的文本内容;text 不能是 null,且必须至少包含一个非空白字符。

2、如果 text 不包含有效的文本内容,则抛出 IllegalArgumentException

isAssignable(Class<?> superType, @Nullable Class<?> subType, String message)

1、断言 subType 是否为 superType 的子类型,如果不是则抛出 IllegalArgumentException 异常。

2、注意必须是子类型,同一类型也会报错

isInstanceOf(Class<?> type, @Nullable Object obj, String message)

1、断言所提供的对象(obj)是所提供类(type)的实例。

2、如果对象不是类型的实例,则抛出 IllegalArgumentException

isNull(@Nullable Object object, String message)

1、断言对象(object)是 null,如果不是 null,则抛出 IllegalArgumentException

notNull(@Nullable Object object, String message)

1、断言对象不是 null,如果是 null,则抛出 IllegalArgumentException

isTrue(boolean expression, String message)

1、断言布尔表达式,如果表达式计算结果为 false,则抛出{@link IllegalArgumentException}。

2、message:断言失败时要使用的异常消息

state(boolean expression, String message)

1、断言布尔表达式,如果表达式的计算结果为 false,则抛出 IllegalArgumentException。

2、和 {@link Assert#isTrue(boolean, java.lang.String)} 实现的效果一致.

noNullElements(@Nullable Object[] array, String message)

1、断言数组不包含 null 元素。

2、array 可以为 null,可以为空,有元素时,只要有一个为 null,则抛出 IllegalArgumentException

notEmpty(@Nullable Collection<?> collection, String message)

1、断言集合包含元素,即不能为 null,也不能为空,必须至少包含一个元素,否则抛出 IllegalArgumentException

notEmpty(@Nullable Map<?, ?> map, String message)

断言 Map 包含元素,即不能为 null,也不能为空,必须至少包含一个元素,否则抛出 IllegalArgumentException

notEmpty(@Nullable Object[] array, String message)

断言 array 包含元素,即不能为 null,也不能为空,必须至少包含一个元素,否则抛出 IllegalArgumentException

ObjectUtils 对象工具类

1、org.springframework.util.ObjectUtils 是 spring-core-x.x.x.RELEASE.jar 核心包下提供的对象工具类,除了提供功能封装之外,还有一个好处就是老板再也不用担心空指针异常。

2、其常用方法如下:

方法

描述

boolean containsElement(@Nullable Object[] array, Object element)

1、检测数组中是否包含指定的元素,array 为 null 时恒为 false

String getDisplayString(@Nullable Object obj)

1、将对象转为可视化的字符串,如果 obj 为 null,则恒返回空字符串""。

2、底层也是调用 {@link ObjectUtils#nullSafeToString(java.lang.Object)} 方法

String getIdentityHexString(Object obj)

1、获取对象唯一的十六进制字符串,实质是将对象的哈希code转成了十六进制字符串

String identityToString(@Nullable Object obj)

1、获取对象的整体标识,obj.getClass().getName() + "@" + getIdentityHexString(obj);

2、如果 obj 为 null,则恒返回空字符串 ""

boolean isArray(@Nullable Object obj)

1、判断对象是否为数组,为 null 时恒返回 false

boolean isCheckedException(Throwable ex)

1、判断异常是否为受检查异常类型,源码为:!(ex instanceof RuntimeException ex instanceof Error)。

2、即不是运行时异常,也不是 Error 时,则判定 ex 为受检查异常

boolean isCompatibleWithThrowsClause(Throwable ex, @Nullable Class<?>... declaredExceptions)

1、判断受检查异常(ex)是否为指定的异常类型。

2、如果 ex 为运行时异常(RuntimeException)或者为 Error,则恒返回 true

boolean isEmpty(@Nullable Object obj)

1、检测对象是否为空,如果为 null 或者为空,则返回 true,字符串的空格不算空,返回 false.。

2、支持以下类型:{@link Optional}、Array、{@link CharSequence}、{@link Collection}、{@link Map}。不是这些类型时,不为 null 时,恒为 false.

boolean isEmpty(@Nullable Object[] array)

1、检查数组是否为空,源码:return (array == null || array.length == 0)

String nullSafeClassName(@Nullable Object obj)

1、获取对象的 className 值,当 obj 为 null 时返回字符串 "null"

boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2)

1、检查两个对象是否相等,当其中任意一个为 null,另一个不为 null 时,恒返回 false。

2、先根据 "==" 判断,然后判断是否其中一个为 null,接着使用 o1.equals(o2) 比较,然后如果两个对象都是数组,则逐个比较其中的元素是否相等,前面4步都判断不出来,则返回false.

int nullSafeHashCode(@Nullable Object obj)

1、获取对象的 哈希 code 值,如果 obj 为null,则返回 0

String nullSafeToString(@Nullable Object obj)

1、返回对象的字符串表现形式,如果 obj 为 null,则返回字符串 "null"

Base64Utils Base64 编解码工具类

import org.springframework.util.Base64Utils;
/**
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/6/21 12:23
 */
public class Base64UtilsTest {

    /**
     * 解码:
     * byte[] decode(byte[] src)
     * byte[] decodeFromString(String src)
     * byte[] decodeFromUrlSafeString(String src)
     * byte[] decodeUrlSafe(byte[] src)
     * 编码:
     * byte[] encode(byte[] src)
     * String encodeToString(byte[] src)
     * String encodeToUrlSafeString(byte[] src)
     * byte[] encodeUrlSafe(byte[] src)
     *
     * @param args
     */
    public static void main(String[] args) {
        String pass = "123456ppx";
        String encodeToString = Base64Utils.encodeToString(pass.getBytes());
        byte[] decodeFromString = Base64Utils.decodeFromString(encodeToString);

        //源内容:123456ppx
        System.out.println("源内容:" + pass);
        //编码后:MTIzNDU2cHB4
        System.out.println("编码后:" + encodeToString);
        //解码后:123456ppx
        System.out.println("解码后:" + new String(decodeFromString));
    }
}

DigestUtils 摘要工具类

方法

描述

byte[] md5Digest(byte[] bytes)

1、对字节数组提取 md5 摘要,返回字节数组

byte[] md5Digest(InputStream inputStream)

2、对字节输入流提取 md5 摘要,返回字节数组,适合对文件进去提取摘要

String md5DigestAsHex(byte[] bytes)

3、对字节数组提取 md5 摘要,以16进制字符串返回

String md5DigestAsHex(InputStream inputStream)

4、对字节输入流提取 md5 摘要,以16进制字符串返回,适合对文件进去提取摘要

StringUtils 字符串工具类

方法

描述

String[] addStringToArray(@Nullable String[] array, String str)

1、往数组中添加元素,数组的大小是固定的,底层是使用 System.arraycopy 将旧数组复制到新数组,所以返回值是添加后的新数组。

2、array 等于 null 或者为空时,会自动创建

String arrayToCommaDelimitedString(@Nullable Object[] arr)

1、将数组转成字符串,元素之间默认使用 "," 连接, arr 为 null 或者为空时,返回空字符串

String arrayToDelimitedString(@Nullable Object[] arr, String delim)

1、将数组转成字符串,并使用指定的字符串进行连接

String capitalize(String str)

1、将字符串的首字母转大写,如果 str 为null或者为空,则原样返回

String collectionToCommaDelimitedString(@Nullable Collection<?> coll)

1、将集合转为字符串,元素之间默认使用 "," 连接,如果 coll 为null或者为空,则返回空字符串

String collectionToDelimitedString(@Nullable Collection<?> coll, String delim)

2、将集合转为字符串,元素之间使用指定字符串连接,如果 coll 为null或者为空,则返回空字符串

String collectionToDelimitedString(@Nullable Collection<?> coll, String delim, String prefix, String suffix)

1、将集合(coll)转为字符串,使用指定字符串(delim)连接元素。

2、prefix、suffix 是连接元素时使用前缀与后缀,源码:sb.append(prefix).append(item.next()).append(suffix);

3、所以非常适合用于连接数据库 in 函数的参数,如: in('99pp','887uy','67tf')。4、如果 coll 为null或者为空,则返回空字符串

Set commaDelimitedListToSet(@Nullable String str)

1、将字符串转为 Set,元素使用英文","符号隔开,如果 str 为 null,则返回空集合。

2、返回的集合为 LinkedHashSet

String[] commaDelimitedListToStringArray(@Nullable String str)

1、将字符串转为 数组,元素使用英文","符号隔开,如果 str 为 null,则返回空数组

String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter)

1、将字符串转为 数组,元素使用指定字符串符号隔开,如果 str 为 null,则返回空数组

String[] concatenateStringArrays(@Nullable String[] array1, @Nullable String[] array2)

1、将两个数组的元素合二为一,成为一个新数组。

2、源码的思路是:如果 array1 为空或者为 null,则直接返回 array2,如果 array2 为空或者为null,则直接返回 array1,最后使用 System.arraycopy 的方式复制新数组

boolean containsWhitespace(@Nullable CharSequence str)

1、检查 str 是否含有空格,空字符串与 null 不算空格

boolean containsWhitespace(@Nullable String str)

1、检查 str 是否含有空格,空字符串与 null 不算空格

int countOccurrencesOf(String str, String sub)

1、检查源字符串(str) 中字符串(sub)出现的次数,如果 str 或者 sub 任意一个为空或者为null,则返回0

String getFilename(@Nullable String path)

1、获取字符串中的文件名称,如 "mypath/myfile.txt" -> "myfile.txt"。

2、如果 path 为 null,则返回 null。路径必须是左斜杠,源码是 path.lastIndexOf("/") 分割取值

String getFilenameExtension(@Nullable String path)

1、获取文件格式,如 "mypath/myfile.txt" -> "txt"。

2、源码: path.lastIndexOf(".") 分割取值

boolean hasLength(@Nullable CharSequence str)

1、检查字符序列是否有长度, str为null或者为空,返回false,否则为true,空格也算有长度

boolean hasLength(@Nullable String str)

1、检查字符串是否有长度, str为null或者为空,返回false,否则为true,空格也算有长度

boolean hasText(@Nullable CharSequence str)

1、检查 str 是否有文本值,空格不算文本,所以 str 为null或者为空,或者空格,都返回 false

boolean hasText(@Nullable String str)

1、检查 str 是否有文本值,空格不算文本,所以 str 为null或者为空,或者空格,都返回 false

boolean isEmpty(@Nullable Object str)

1、判断对象是否为空,或者为nul,源码:(str == null || "".equals(str))

String[] sortStringArray(String[] array)

1、对数组的中元素进行排序,如果 array 为null或者为空,则返回空数组。

2、数字在前,单词次之,汉字最末,根据 ascii 码排序,底层用的 Arrays.sort(array)

String[] toStringArray(Collection collection)

1、将 {@link Collection} 转为数组

String[] toStringArray(Enumeration enumeration)

1、将 {@link Enumeration} 转为数组

String trimAllWhitespace(String str)

去掉 str 中的所有空格

String[] trimArrayElements(String[] array)

去掉数组中所有元素前后的空格

FileSystemUtils 文件系统工具类

方法

描述

void copyRecursively(File src, File dest)

void  copyRecursively(Path src, Path dest)

1、递归复制源文件或者目录到目标文件或目录,底层使用 {@link Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}

2、src、dest 不能为 null,否则非法参数异常。3、src 不存在时抛异常,dest 不存在时会自动创建

boolean deleteRecursively(@Nullable File root)

boolean deleteRecursively(@Nullable Path root)

1、递归删除,root 为null,或者不存在,都返回 false。底层使用 {@link Files#delete(java.nio.file.Path)}

CollectionUtils 集合工具类

方法

描述

boolean contains(@Nullable Enumeration<?> enumeration, Object element)

1、检查 enumeration、iterator 中是否含有指定的元素,底层使用 {@link ObjectUtils#nullSafeEquals(java.lang.Object, java.lang.Object)}

2、如果 iterator 为 null,则直接返回 false

boolean contains(@Nullable Iterator<?> iterator, Object element)

Class<?> findCommonElementType(Collection<?> collection)

1、获取集合中公共的元素类型,集合为null或者为空时,返回 null。

2、集合中元素如果有多种类型,则返回 null,会遍历其中某一个元素

boolean isEmpty(@Nullable Collection<?> collection)

boolean isEmpty(@Nullable Map<?, ?> map)

1、判断集合或者map是否为null或者为空,源码:(collection == null || collection.isEmpty())

void mergeArrayIntoCollection(@Nullable Object array, Collection collection)

1、将数组元素添加到集合中

void mergePropertiesIntoMap(@Nullable Properties props, Map<K, V> map)

1、将属性文件(props)中的值添加/提取到 map 中

SerializationUtils 序列化工具类

1、byte[] serialize(@Nullable Object object):对象序列化

2、Object deserialize(@Nullable byte[] bytes):对象反序列化

import com.wmx.apachestudy.pojo.Person;
import org.springframework.util.SerializationUtils;
import java.util.Date;
/**
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/6/21 13:56
 */
public class SerializationUtilsTest {

    public static void main(String[] args) {
        //被序列化的实体必须 implements Serializable 接口
        Person person = new Person(1001,"华安",new Date(),8998.87f);
        byte[] serialize = SerializationUtils.serialize(person);
        Object deserialize = SerializationUtils.deserialize(serialize);
        System.out.println(deserialize);
    }
}

StopWatch 秒表 

/**
     * StopWatch():建造一个新的秒表,不启动任何任务。
     * void start():启动未命名任务
     * start(String taskName):启动命名任务,如果任务已经启动,则 IllegalStateException
     * * taskName要启动的任务的名称
     * stop():停止当前任务,如果任务已经停止,则 IllegalStateException
     * long getTotalTimeMillis():返回所有任务的总时间(毫秒)。
     * double getTotalTimeSeconds():返回所有任务的总时间(以秒为单位)。
     * String toString():返回描述所执行的所有任务的信息字符串
     *
     * @throws InterruptedException
     */
    @Test
    public void testStopWatch1() throws InterruptedException {
        StopWatch stopWatch = new StopWatch();

        int nextInt = new SecureRandom().nextInt(4000);
        System.out.println(nextInt);//1236

        stopWatch.start("wmx");
        TimeUnit.MILLISECONDS.sleep(nextInt);

        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeMillis() + "(毫秒)");//1237(毫秒)
        System.out.println(stopWatch.getTotalTimeSeconds() + "(秒)");//1.237(秒)
        System.out.println(stopWatch.toString());//StopWatch '': running time (millis) = 1237; [wmx] took 1237 = 100%
    }

BeanUtils 内审与反射工具类

BeanUtils 用于实例化 bean、检查 bean 属性类型、复制 bean 属性等。

/**
     * copyProperties(Object source, Object target):将给定源 bean 的属性值复制到目标 bean 中。
     * copyProperties(Object source, Object target, Class<?> editable)
     * copyProperties(Object source, Object target, String... ignoreProperties)
     * 1、只要属性匹配,源类和目标类就不必相互匹配,甚至不必相互派生。
     * 2、源 bean 公开但目标 bean 不公开的任何 bean 属性都将被忽略。
     * 3、只能是单个 POJO 对象,不能是 List<POJO>,也不能是 Map 对象.
     * 4、只能是 Java bean 直接的属性赋值,不能 Java bean -> Map,或者 Map -> Java Bean。
     * 5、editable:表示只设置在给定“可编辑”类(或接口)中定义的属性。
     * 6、ignoreProperties:表示忽略某些属性,不进行复制,则目标 bean 的这些属性会为 null.
     */
    @Test
    public void testCopyProperties() {
        Book book = new Book("a1", "三国演义", 78.88F, new Date(), true, 1000);
        Book book1 = new Book();
        BeanUtils.copyProperties(book, book1, "publishDate", "stock");

        book.setStock(999);
        book1.setPrice(88.88F);
        //Book{bid='a1', title='三国演义', price=78.88, publishDate=Tue Dec 07 19:10:20 CST 2021, isShow=true, stock=999}
        System.out.println(book);
        //Book{bid='a1', title='三国演义', price=88.88, publishDate=Tue Dec 07 19:10:20 CST 2021, isShow=true, stock=1000}
        System.out.println(book1);
    }

属性复制流行库对比

URI 编解码工具类 UriUtils 

1、Springframework UriUtils 是基于 RFC3986 的 URI 编码和解码实用工具类。

2、encodeXyz 编码方法:它们对特定 URI 组件(例如路径、查询参数)进行百分比编码,对非法字符进行编码,其中包括非 US-ASCII 字符,以及在给定 URI 中非法的字符 URI 组件类型,如 RFC 3986中定义的。此方法在编码方面的效果与使用多参数构造函数相当。

3、encode 和 encodeUriVariables 编码方法:可以通过对 URI 中任何位置的非法字符或具有任何保留含义的字符进行百分比编码来对URI变量值进行编码。

/**
     * 使用给定的编码对给定的URI查询参数值进行编码(不包括等于符号)
     * String encodeQuery(String query, Charset charset)
     * String encodeQuery(String query, String encoding)
     */
    @Test
    public void testEncodeQuery() {
        String sourceUri = "https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=冬奥会&wf_state=001|004";

        String encodeHost1 = UriUtils.encodeQuery(sourceUri, Charset.forName("UTF-8"));
        String encodeHost2 = UriUtils.encodeQuery(sourceUri, Charset.forName("gbk"));

        //https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=%E5%86%AC%E5%A5%A5%E4%BC%9A&wf_state=001%7C004
        System.out.println("encodeHost1=" + encodeHost1);
        //https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=%B6%AC%B0%C2%BB%E1&wf_state=001%7C004
        System.out.println("encodeHost2=" + encodeHost2);

        String decodeHost1 = UriUtils.decode(encodeHost1, Charset.forName("UTF-8"));
        String decodeHost2 = UriUtils.decode(encodeHost2, Charset.forName("gbk"));

        //https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=冬奥会&wf_state=001|004
        System.out.println("decodeHost1=" + decodeHost1);
        System.out.println("decodeHost2=" + decodeHost2);
    }

请求参数工具类 ServletRequestUtils

1、ServletRequestUtils 用于获取 http 请求地址上的查询参数,并转为需要的数据类型,默认 HttpServletRequest 获取的参数值都是字符串类型。

/**
     * springframework web {@link ServletRequestUtils} 获取查询参数值
     * http://localhost:8080/servlet/getParameters2/1993?token=2f2ef70923323&year=2022&price=105.89&isShow=true
     * <p>
     * Boolean getBooleanParameter(ServletRequest request, String name)
     * Double getDoubleParameter(ServletRequest request, String name)
     * Float getFloatParameter(ServletRequest request, String name)
     * Integer getIntParameter(ServletRequest request, String name)
     * Long getLongParameter(ServletRequest request, String name)
     * String getStringParameter(ServletRequest request, String name)
     * <p>
     * 1、name 参数名称不存在时,默认返回 null。
     * 2、name 参数名称存在,但是值无法解析为 double、flout、int、long 时,则报错 NumberFormatException(为空也会解析报错).
     * 3、解析 boolean 值时,true、yes、1 都会作为 true,其它任意字符都会解析为 boolean 值的 false。
     *
     * @param request
     * @return
     */
    @GetMapping("servlet/getParameters2/1993")
    @SuppressWarnings("all")
    public Map<String, Object> testGetParameters2(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>(8);
        try {
            String token = ServletRequestUtils.getStringParameter(request, "token");
            Boolean isShow = ServletRequestUtils.getBooleanParameter(request, "isShow");
            Long year = ServletRequestUtils.getLongParameter(request, "year");
            Double price = ServletRequestUtils.getDoubleParameter(request, "price");

            dataMap.put("token", token);
            dataMap.put("year", year);
            dataMap.put("price", price);
            dataMap.put("isShow", isShow);
        } catch (ServletRequestBindingException e) {
            e.printStackTrace();
        }
        //{"year":2022,"price":105.89,"token":"2f2ef70923323","isShow":true}
        return dataMap;
    }

FileCopyUtils 文件复制

从文件中读入到字节数组中:byte[] copyToByteArray(File in)
从输入流中读入到字节数组中:byte[] copyToByteArray(InputStream in)
从输入流中读入到字符串中:String copyToString(Reader in)
从字节数组到文件:void copy(byte[] in, File out)
从文件到文件:int copy(File in, File out)
从字节数组到输出流:void copy(byte[] in, OutputStream out) 
从输入流到输出流:int copy(InputStream in, OutputStream out) 
从输入流到输出流:int copy(Reader in, Writer out)
从字符串到输出流:void copy(String in, Writer out)

ReflectionUtils 反射工具类

Method findMethod(Class<?> clazz, String name) 在类中查找指定方法
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)  同上,额外提供方法参数类型作查找条件
Method[] getAllDeclaredMethods(Class<?> leafClass)  获得类中所有方法,包括继承而来的
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes) 在类中查找指定构造方法
boolean isEqualsMethod(Method method)  是否是 equals() 方法
boolean isHashCodeMethod(Method method) 是否是 hashCode() 方法 
boolean isToStringMethod(Method method) 是否是 toString() 方法
boolean isObjectMethod(Method method) 是否是从 Object 类继承而来的方法
boolean declaresException(Method method, Class<?> exceptionType) 检查一个方法是否声明抛出指定异常
Object invokeMethod(Method method, Object target)  执行方法
Object invokeMethod(Method method, Object target, Object... args)  同上,提供方法参数
void makeAccessible(Method method)  取消 Java 权限检查。以便后续执行该私有方法
void makeAccessible(Constructor<?> ctor)  取消 Java 权限检查。以便后续执行私有构造方法
Field findField(Class<?> clazz, String name) 在类中查找指定属性
Field findField(Class<?> clazz, String name, Class<?> type) 同上,多提供了属性的类型
boolean isPublicStaticFinal(Field field) 是否为一个 "public static final" 属性
Object getField(Field field, Object target) 获取 target 对象的 field 属性值
void setField(Field field, Object target, Object value)  设置 target 对象的 field 属性值,值为 value
void shallowCopyFieldState(Object src, Object dest) 同类对象属性对等赋值
void makeAccessible(Field field)  取消 Java 的权限控制检查。以便后续读写该私有属性
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc) 对类的每个属性执行 callback
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)  同上,多了个属性过滤功能。
void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc) 同上,但不包括继承而来的属性

ResourceUtils 资源文件工具类

1、org.springframework.util.ResourceUtils:用于将资源位置解析为文件系统中的文件的实用程序方法。主要用于框架内部使用。

2、JAR、War 包内部的文件无法获取,必须是一个独立的文件,即项目打包后,无法再获取包中的文件。

boolean isUrl(String resourceLocation):判断字符串是否是一个合法的 URL 字符串。
boolean isFileURL(URL url):确定给定的URL是否指向文件系统中的资源: 
boolean isJarFileURL(URL url):确定给定的URL是否指向jar文件本身,即是否具有协议“file”,并以“.jar”扩展名结尾。
boolean isJarURL(URL url):确定给定的URL是否指向jar文件中的资源。具有协议“jar”、“war”、“zip”、“vfszip”或“wsjar”。
URL getURL(String resourceLocation):获取 URL。
URL extractJarFileURL(URL jarUrl):从给定的URL中提取实际jar文件的URL(可能指向jar文件中的资源或jar文件本身)。

获取文件(JAR 包内部的文件无法获取,必须是一个独立的文件),即项目打包后,无法再获取包中的文件。
	File getFile(String resourceLocation)
       resourceLocation:要解析的资源位置:"classpath:" 伪URL,类路径资源;"file:" URL或纯文件路径
	File getFile(URI resourceUri)
	File getFile(URL resourceUrl)
@GetMapping("resourceUtils/read1")
    public ResultData resourceUtils1() {
        try {
            File file = ResourceUtils.getFile("classpath:application.yml");
            List<String> list = FileUtil.readUtf8Lines(file);
            return ResultData.success(list);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultData.error(ResultCode.FAIL, e);
        }
    }

StreamUtils 流工具类

1、处理流的简单实用方法。此类的复制方法与{@link FileCopyUtils}中定义的复制方法类似,只是所有受影响的流在完成后都保持打开状态。

2、所有复制方法都使用4096字节的块大小。

void copy(byte[] in, OutputStream out):复制到输出流
int copy(InputStream in, OutputStream out):复制到输出流
void copy(String in, Charset charset, OutputStream out):复制到输出流
long copyRange(InputStream in, OutputStream out, long start, long end):复制输入流中指定位置的内容
byte[] copyToByteArray(InputStream in):复制到字节数组
String copyToString(InputStream in, Charset charset):复制到字符串
int drain(InputStream in):// 舍弃输入流中的内容
InputStream emptyInput():返回一个空的输入流

LinkedCaseInsensitiveMap 不区分大小 key

/**
     * {@link org.springframework.util.LinkedCaseInsensitiveMap} 以不区分大小写的方式存储字符串的 key 。
     * key 不支持存储 null.
     */
    @Test
    public void testLinkedCaseInsensitiveMap() {
        Map<String, Object> caseInsensitiveMap = new LinkedCaseInsensitiveMap<>();
        caseInsensitiveMap.put("code", 200);
        caseInsensitiveMap.put("msg", "key 不区分大小写");

        // {code=200, msg=key 不区分大小写}
        System.out.println(caseInsensitiveMap);
        // 200
        System.out.println(caseInsensitiveMap.get("CODE"));
        caseInsensitiveMap.put("CODE", 500);
        // 500
        System.out.println(caseInsensitiveMap.get("code"));
    }

Resource 资源描述符

1、资源描述符的接口,该描述符从底层资源(如文件或类路径资源)的实际类型进行抽象。如果每个资源以物理形式存在,则可以为其打开InputStream,但对于某些资源,只能返回URL或File句柄。

2、常用的实现类如下:

实现类

描述

WritableResource

ContextResource

UrlResource

 java.net.URL 定位器的 Resource 实现。在 “File:” 协议的情况下,支持解析为 URL 和 File 。

FileUrlResource

只支持绝对路径。如 new FileUrlResource("E:\temp\xxx.yml")。

FileSystemResource

java.io.File 和 java.nio.File.Path 的 Resource 实现,使用文件系统目标进行处理。支持解析为 File 和 URL。

ClassPathResource

类路径资源,读取类路径下下的任意资源文件,如果路径有前缀 / 也会自动被去掉,

ByteArrayResource

为给定的字节数组创建 ByteArrayInputStream 。对于从本地内容创建邮件附件特别有用,因为JavaMail需要能够多次读取流。

InputStreamResource

PathResource

即支持绝对路径,如 /app/xx.yml,也支持相对路径,如  ./xx.yml,../../xx.yml

如 new PathResource(“./xx.yml”)。