ObjectUtils
org.springframework.util.ObjectUtils 有很多处理 null object 的方法. 如
- nullSafeHashCode,
- nullSafeEquals,
- isArray,
- containsElement,
- addObjectToArray, 等有用的方法
获取对象基本信息
static String nullSafeClassName(Object obj) // 获取对象的类名。参数为 null 时,返回"null"。
static String getIdentityHexString(Object obj) // 获取对象 HashCode(十六进制形式字符串)。参数为 null 时,返回 0 。
static String identityToString(Object obj) // 获取对象的类名和 HashCode。 参数为 null 时,返回 "" 。
static String getDisplayString(Object obj) // 相当于 toString()方法,但参数为 null 时,返回:""
static int hashCode(boolean bool) // 被废弃,建议使用jdk8原生hashCode方法。
判断工具
static boolean isEmpty(Object[] array) // 判断数组是否为空。
static boolean isArray(Object obj) // 判断参数对象是否是数组。
static boolean containsElement(Object[] array, Object element) // 判断数组中是否包含指定元素。
static boolean isEmpty(Object obj)
/**
*判断参数对象是否为空,判断标准为:
* Optional: considered empty if Optional.empty()
* Array: considered empty if its length is zero
* CharSequence: considered empty if its length is zero
* Collection: delegates to Collection.isEmpty()
* Map: delegates to Map.isEmpty()
*/
NullSafe “替代” Object 原生方法
static boolean nullSafeEquals(Object o1, Object o2) // 相等,或同为 null时,返回 true
static int nullSafeHashCode(Object object) // 参数为 null 时,返回 0
static String nullSafeToString(boolean[] array) // 参数为 null 时,返回"null"
其他工具
static <A,O extends A>
A[] addObjectToArray(A[] array, O obj) // 向参数数组的末尾追加新元素,并返回一个新数组。
static Object[] toObjectArray(Object source) // 原生基础类型数组 --> 包装类数组
StringUtils
字符串判断
static boolean isEmpty(Object str) // 判断字符串是否为null,或""。注意,包含空白符的字符串为非空。
static boolean endsWithIgnoreCase(String str, String suffix) // 判断字符串是否是以指定内容结束。忽略大小写。
static boolean startsWithIgnoreCase(String str, String prefix) // 判断字符串是否已指定内容开头。忽略大小写。
static boolean containsWhitespace(String str) // 是否包含空白符
static boolean hasLength(CharSequence str) // 判断字符串非空且长度不为 0。
static boolean hasText(CharSequence str) // 判断字符串是否包含实际内容(即非仅包含空白符)
static boolean substringMatch(CharSequence str, int index, CharSequence substring) // 判断字符串指定索引处是否包含一个子串。
static int countOccurrencesOf(String str, String sub) // 计算一个字符串中指定子串的出现次数。
字符串数组操作
static String[] addStringToArray(String[] array, String str) // 向参数字符串数组的末尾添加新的字符串,并返回新数组。
static String[] concatenateStringArrays(String[] array1, String[] array2) // 将两个字符串数组合并成一个字符串数组。其中重复的元素会出现两次。
static String[] mergeStringArrays(String[] array1, String[] array2) // 被废弃,建议通过 LinkedHashSet 手动合并两个字符串。
static String[] removeDuplicateStrings(String[] array) //Remove duplicate strings from the given array.
static String[] sortStringArray(String[] array) // 对给定字符串数组进行排序,并返回排序后的新数组。
字符串 <–> 数组/集合 互转
/** 集合/数组 转 字符串。**/
static String arrayToCommaDelimitedString(Object[] arr) // 以 “,” 作为分隔符。
static String arrayToDelimitedString(Object[] arr, String delim) // 第二个参数手动指定分隔符。
static String collectionToCommaDelimitedString(Collection<?> coll) // 以“,”作为分隔符。
static String collectionToDelimitedString(Collection<?> coll, String delim) // 第二个参数手动指定分隔符。
static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) // 集合中每一个元素的字符串前后可以加上前缀和后缀。
/** 字符串 转 数组/集合 **/
static String[] split(String toSplit, String delimiter) // 以指定分隔符切分成字符串,切割成两份。
static String[] tokenizeToStringArray(String str, String delimiters) // 以指定分隔符(可以是多个)切分字符串
static Set<String> commaDelimitedListToSet(String str) // 以“,”作为分隔符
static String[] commaDelimitedListToStringArray(String str) // 以“,”作为分隔符。
static String[] delimitedListToStringArray(String str, String delimiter) // 以指定分隔符进行切割
static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) // 切割字符串的同时,删除指定字符(可以使多个)
/** 其他转换 **/
static String[] toStringArray(Collection<String> collection) // 将字符串集合转变为字符串数组。
字符“修正”
增加新内容
static String quote(String str) // 加上单引号
static Object quoteIfString(Object obj) // 同上。如果参数是非字符串,则返回参数对象。
删除内容
static String trimTrailingCharacter(String str, char trailingCharacter) // 去除尾部的特定字符。
static String trimLeadingCharacter(String str, char leadingCharacter) // 去除头部的特定字符。
static String trimLeadingWhitespace(String str) // 去除头部的空白符。
static String trimTrailingWhitespace(String str) // 去除头部的空白符。
static String trimWhitespace(String str) // 去除头部和尾部的空白符。
static String trimAllWhitespace(String str) // 删除开头、结尾和中间的空白符。
static String delete(String inString, String pattern) // 删除指定子串
static String deleteAny(String inString, String charsToDelete) // 删除指定字符(可以是多个)
static String[] trimArrayElements(String[] array) // 对数组的每一项执行 trim() 方法。
修改原内容
static String replace(String inString, String oldPattern, String newPattern) // 查找指定子串,替换成指定新内容。
static String capitalize(String str) // 每个单词的首字母大写。
static String uncapitalize(String str) // 每个单词的首字母小写。
static String uriDecode(String source, Charset charset) // 将URL字符串进行解码
截取
static String unqualify(String qualifiedName) // 以“.”作为分隔符,获取其最后一部分。
static String unqualify(String qualifiedName, char separator) // 以指定字符作为分隔符,获取其最后一部分。
文件路径字符串操作
static String cleanPath(String path) // 解析路径字符串中的“..”,返回更简洁的字符串路径。
static String getFilename(String path) // 从一个路径字符串中解析出文件名部分。
static String getFilenameExtension(String path) // 从一个路径字符串中解析出文件后缀名部分。
static boolean pathEquals(String path1, String path2) // 比较两个路径字符串是否是同一个路径名。会自动处理路径中的“..”。
static String stripFilenameExtension(String path) // 剥离文件路径名中后缀部分。
static String applyRelativePath(String path, String relativePath) // 在一个路径(通常是绝对路径,需要以“/”结束)之后,添加相对于它为起点的相对路径文件名。
其他
static Properties splitArrayElementsIntoProperties(String[] array, String delimiter)
// 将字符串数组中的每一项,按照指定分隔符进行切分,并生成 Properties 对象。
// 字符串数组的内容类似于:new String[]{"key1,value1", "key2,value2", "key3,value3"}
static Properties splitArrayElementsIntoProperties(String[] array, String delimiter, String charsToDelete)
static TimeZone parseTimeZoneString(String timeZoneString)
// 通过解析时区字符串生成时区对象。
// 常见 TimeZone 字符串见最后。
TimeZone 地点
“Asia/Shanghai” 中国标准时间 (北京)
“Asia/Hong_Kong” 香港时间 (香港)
“Asia/Taipei” 台北时间 (台北)
“Asia/Seoul” 首尔
“Asia/Tokyo” 日本时间 (东京)
“America/New_York” 美国东部时间 (纽约)
“America/Denver” 美国山区时间 (丹佛)
“America/Costa_Rica” 美国中部时间 (哥斯达黎加)
“America/Chicago” 美国中部时间 (芝加哥)
“America/Mexico_City” 美国中部时间 (墨西哥城)
“America/Regina” 美国中部时间 (里贾纳)
“America/Los_Angeles” 美国太平洋时间 (洛杉矶)
“Pacific/Majuro” 马朱罗
“Pacific/Midway” 中途岛
“Pacific/Honolulu” 檀香山
“America/Anchorage” 安克雷奇
“America/Tijuana” 美国太平洋时间 (提华纳)
“America/Phoenix” 美国山区时间 (凤凰城)
“America/Chihuahua” 奇瓦瓦
“America/Bogota” 哥伦比亚时间 (波哥大)
“America/Caracas” 委内瑞拉时间 (加拉加斯)
“America/Barbados” 大西洋时间 (巴巴多斯)
“America/Manaus” 亚马逊标准时间 (马瑙斯)
“America/St_Johns” 纽芬兰时间 (圣约翰)
“America/Santiago” 圣地亚哥
“America/Argentina/Buenos_Aires” 布宜诺斯艾利斯
“America/Godthab” 戈特霍布
“America/Montevideo” 乌拉圭时间 (蒙得维的亚)
“America/Sao_Paulo” 圣保罗
“Atlantic/South_Georgia” 南乔治亚
“Atlantic/Azores” 亚述尔群岛
“Atlantic/Cape_Verde” 佛得角
“Africa/Casablanca” 卡萨布兰卡
“Europe/London” 格林尼治标准时间 (伦敦)
“Europe/Amsterdam” 中欧标准时间 (阿姆斯特丹)
“Europe/Belgrade” 中欧标准时间 (贝尔格莱德)
“Europe/Brussels” 中欧标准时间 (布鲁塞尔)
“Europe/Sarajevo” 中欧标准时间 (萨拉热窝)
“Africa/Brazzaville” 西部非洲标准时间 (布拉扎维)
“Africa/Windhoek” 温得和克
“Asia/Amman” 东欧标准时间 (安曼)
“Europe/Athens” 东欧标准时间 (雅典)
“Asia/Beirut” 东欧标准时间 (贝鲁特)
“Africa/Cairo” 东欧标准时间 (开罗)
“Europe/Helsinki” 东欧标准时间 (赫尔辛基)
“Asia/Jerusalem” 以色列时间 (耶路撒冷)
“Africa/Harare” 中部非洲标准时间 (哈拉雷)
“Europe/Minsk” 明斯克
“Asia/Baghdad” 巴格达
“Europe/Moscow” 莫斯科
“Asia/Kuwait” 科威特
“Africa/Nairobi” 东部非洲标准时间 (内罗毕)
“Asia/Tehran” 伊朗标准时间 (德黑兰)
“Asia/Baku” 巴库
“Asia/Tbilisi” 第比利斯
“Asia/Yerevan” 埃里温
“Asia/Dubai” 迪拜
“Asia/Kabul” 阿富汗时间 (喀布尔)
“Asia/Karachi” 卡拉奇
“Asia/Oral” 乌拉尔
“Asia/Yekaterinburg” 叶卡捷林堡
“Asia/Calcutta” 加尔各答
“Asia/Colombo” 科伦坡
“Asia/Katmandu” 尼泊尔时间 (加德满都)
“Asia/Almaty” 阿拉木图
“Asia/Rangoon” 缅甸时间 (仰光)
“Asia/Krasnoyarsk” 克拉斯诺亚尔斯克
“Asia/Bangkok” 曼谷
“Asia/Irkutsk” 伊尔库茨克时间 (伊尔库茨克)
“Asia/Kuala_Lumpur” 吉隆坡
“Australia/Perth” 佩思
“Asia/Yakutsk” 雅库茨克时间 (雅库茨克)
“Australia/Darwin” 达尔文
“Australia/Brisbane” 布里斯班
“Asia/Vladivostok” 海参崴时间 (符拉迪沃斯托克)
“Pacific/Guam” 关岛
“Australia/Adelaide” 阿德莱德
“Australia/Hobart” 霍巴特
“Australia/Sydney” 悉尼
“Asia/Magadan” 马加丹时间 (马加丹)
“Pacific/Auckland” 奥克兰
“Pacific/Fiji” 斐济
“Pacific/Tongatapu” 东加塔布
CollectionUtils
判断工具
static boolean isEmpty(Collection<?> collection) // 判断集合是否为空。
static boolean isEmpty(Map<?,?> map) // 判断Map是否为空
static boolean containsInstance(Collection<?> collection, Object element) // 判断集合中是否包含某个对象
static boolean contains(Iterator<?> iterator, Object element) // 通过迭代器判断某个对象是否在集合中。
static boolean containsAny(Collection<?> source, Collection<?> candidates) // 判断集合中是否包含某些对象中的任意一个。
static boolean hasUniqueObject(Collection<?> collection) // 判断集合中的每个元素是否唯一。即集合中不存在重复元素。
向集合中添加
static <E> void mergeArrayIntoCollection(Object array, Collection<E> collection) // 将数组中的元素都添加找集合中。
static <K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map) // 将 Properties 中的键值对都添加到 Map 中。
在集合中查找
static <T> T lastElement(List<T> list) // 返回 List 中最后一个元素。
static <T> T lastElement(Set<T> set) // 返回 Set 中最后一个元素。
static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) // 返回 candidates 中第一个存在于 source 中的元素。
static <T> T findValueOfType(Collection<?> collection, Class<T> type) // 返回集合中指定类型的元素。
static Object findValueOfType(Collection<?> collection, Class<?>[] types) // 返回集合中指定类型的元素。如果第一种类型未找到,则查找第二种类型,以此类推。
static Class<?> findCommonElementType(Collection<?> collection) // 返回集合中元素的类型
MultiMap 相关
static <K,V> MultiValueMap<K,V> toMultiValueMap(Map<K, List<V>> map) // 将一个 Map<K, List<V>> 对象转换成一个 MultiValueMap <K, V> 对象。
static <K,V> MultiValueMap<K,V> unmodifiableMultiValueMap(MultiValueMap<? extends K,? extends V> map)
// 返回 MultiValueMap 对象的一个不可变视图。
其他
static List arrayToList(Object source) // 将数组转换成链表。
Assert 断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:
if (name == null || name.equls("")) {
throw new IllegalArgumentException("参数错误!");
}
Assert
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用 Assert 工具类上面的代码可以简化为:
Assert.hasText((name, "参数错误!");
这样可以大大增强代码的可读性。
Assert 类中的常用断言方法:
- notNull(Object object, String message)
当 object 为非空(Not Null)时继续执行,否则抛出异常。message 参数用于定制异常信息。和 notNull() 方法断言规则相反的方法是 isNull(Object object, String message),它要求参数为空(Null)才予以“放行”。 - isTrue(boolean expression, String message)
当 expression 表达式结果为真(True)时继续执行,否则抛出异常。 - notEmpty(Collection collection, String message)
当参数即可非空(Not Empty)时继续执行,否则抛出异常。它有多种重载形式。 - hasLength(String text, String message)
当参数 text 有长度(即长度不为0)时继续执行,否则抛出异常。 - hasText(String text, String message)
当参数 text 有内容(即长度不为0,且不全是空白符)时继续执行,否则抛出异常。 - isInstanceOf(Class type, Object obj, String message)
当参数 obj 是指定类型的实例时继续执行,否则抛出异常。 - isAssignable(Class superType, Class subType, String message)
当参数 subType 是参数 superType 的子类时继续执行,否则抛出异常。