Spring Framework spring-core 核心包工具類

目錄

Assert 斷言工具類

ObjectUtils 對象工具類

Base64Utils Base64 編解碼工具類

DigestUtils 摘要工具類

StringUtils 字符串工具類

FileSystemUtils 文件系統工具類

CollectionUtils 集合工具類

SerializationUtils 序列化工具類


1、現在的 Java 開發基本離不開 springframework,而其中 spring-core-x.x.x.RELEASE.jar 核心包下提供了很多實用的工具類,開發中可以直接使用,沒必要再自己重複的造輪子。

2、個人覺得 org.springframework.util 包下面的工具類與 apache 提供的工具類雖然大部分相差無幾,但還是有互補的地方,開發中基本能滿足常用的工具類使用。

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

在線源碼查看:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/AssertTest.java

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}

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"

在線源碼:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/ObjectUtilsTest.java

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進制字符串返回,適合對文件進去提取摘要

在線源碼:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/Base64UtilsTest.java

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) 去掉數組中所有元素前後的空格

在線源碼:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/StringUtilsTest.java

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)}

在線源碼:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/FileSystemUtilsTest.java

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 中

在線源碼:https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/CollectionUtilsTest.java

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);
    }
}

在線源碼 https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/spring/SerializationUtilsTest.java

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章