最近有些小伙伴,希望我分享一些好用的工具類,幫他們提升開發效率。
今天這篇文章專門跟大家一起總結一下,Spring框架本身自帶的一些好用的工具類,希望對你會有所幫助。
很多時候,我們需要在代碼中做判斷:如果不滿足條件,則拋異常。
有沒有統一的封裝呢?
其實Spring給我們提供了Assert類,它表示斷言。
斷言參數是否空,如果不滿足條件,則直接拋異常。
String str = null;Assert.isNull(str, "str必須為空");Assert.isNull(str, () -> "str必須為空");Assert.notNull(str, "str不能為空");
如果不滿足條件就會拋出IllegalArgumentException異常。
斷言集合是否空,如果不滿足條件,則直接拋異常。
List<String> list = null;Map<String, String> map = null;Assert.notEmpty(list, "list不能為空");Assert.notEmpty(list, () -> "list不能為空");Assert.notEmpty(map, "map不能為空");
如果不滿足條件就會拋出IllegalArgumentException異常。
斷言是否滿足某個條件,如果不滿足條件,則直接拋異常。
List<String> list = null;Assert.isTrue(CollectionUtils.isNotEmpty(list), "list不能為空");Assert.isTrue(CollectionUtils.isNotEmpty(list), () -> "list不能為空");
當然Assert類還有一些其他的功能,這里就不多介紹了。
在我們日常開發過程中,對字符串的操作是非常頻繁的,但JDK提供的對于字符串操作的方法,過于簡單,無法滿足我們開發中的需求。
其實Spring提供了工具類StringUtils,對JDK中一些字符串的操作進行了擴展。
StringUtils類其實有個isEmpty()方法判斷,不過已經被廢棄了。
我們可以改成使用hasLength()方法判斷,例如:
if (!StringUtils.hasLength("")) { System.out.println("字符串為空");}
對于后端的很多接口,經常需要去掉前后空格,我們可以使用String類的trim(),但是如果要同時去掉中間的空格呢?
可以使用StringUtils類的trimAllWhitespace方法。
例如:
@Testpublic void testEmpty() { System.out.println("1" + StringUtils.trimAllWhitespace(" 蘇三說技術 測試 ") + "1");}
這個方法執行接口:1蘇三說技術測試1,會把中間的空格也去掉了。
要判斷一個字符串,是不是以某個固定字符串開頭或者結尾,是非常常見的需求。
我們可以使用StringUtils類的startsWithIgnoreCase和endsWithIgnoreCase,可以忽略大小寫比較字符串。
例如:
@Testpublic void testEmpty() { System.out.println(StringUtils.startsWithIgnoreCase("蘇三說技術", "蘇三")); System.out.println(StringUtils.endsWithIgnoreCase("蘇三說技術", "技術"));}
該方法的執行結果會返回兩個true。
有時候我們需要將某個字符串集合的所有元素,拼接成一個字符串,用逗號隔開。
這種場景可以使用StringUtils類的collectionToCommaDelimitedString方法。
例如:
@Testpublic void testEmpty() { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); System.out.println(StringUtils.collectionToCommaDelimitedString(list));}
該方法的執行結果:a,b,c
這個工具類里面還有很多有用的方法:
在我們日常開發當中,經常會遇到集合,比如:list判空的情況。
其實Spring專門為我們提供了,給集合判空的工具類:CollectionUtils
,它位于org.springframework.util包下。
對于一些簡單的集合判斷,集合中是否包含某個元素,集合轉數組,用這個工具還是非常方便的。
通過CollectionUtils工具類的isEmpty方法可以輕松判斷集合是否為空。
例如:
List<Integer> list = new ArrayList<>();list.add(2);list.add(1);list.add(3);if (CollectionUtils.isEmpty(list)) { System.out.println("集合為空");}
通過CollectionUtils工具類的contains方法,可以判斷元素在集合中是否存在。
例如:
List<Integer> list = new ArrayList<>();list.add(2);list.add(1);list.add(3);if (CollectionUtils.contains(list.iterator(), 3)) { System.out.println("元素存在");}
在判斷時需要先調用集合的iterator()方法。
Spring為我們專門提供了一個對象操作工具:ObjectUtils,也在org.springframework.util包下。
里面有很多非常有用的方法。
之前已經介紹過字符串判空工具類StringUtils,和集合的判空工具類CollectionUtils。
而ObjectUtils工具的判空更強大,支持:對象、字符串、集合、數組、Optional、Map的判斷。
例如:
@Testpublic void testEmpty() { String a = "123"; Integer b = new Integer(1); List<String> c = new ArrayList<>(); Integer[] d = new Integer[]{b}; c.add(a); Map<String, String> e = new HashMap<>(); e.put(a, a); Optional<String> f = Optional.of(a); if (!ObjectUtils.isEmpty(a)) { System.out.println("a不為空"); } if (!ObjectUtils.isEmpty(b)) { System.out.println("b不為空"); } if (!ObjectUtils.isEmpty(c)) { System.out.println("c不為空"); } if (!ObjectUtils.isEmpty(d)) { System.out.println("d不為空"); } if (!ObjectUtils.isEmpty(e)) { System.out.println("e不為空"); } if (!ObjectUtils.isEmpty(f)) { System.out.println("f不為空"); }}
這6種對象的判空都支持,非常強大。
之前我們用Objects.equals方法,判斷兩個對象是否相等,經常會出現空指針問題。
而ObjectUtils類提供了安全的判斷兩個對象相等的方法:nullSafeEquals。
例如:
@Testpublic void testEquals() { String a = "123"; String b = null; System.out.println(ObjectUtils.nullSafeEquals(a, b));}
這個例子返回的是false,不會出現空指針的問題。
甚至可以判斷兩個數組是否相等。
例如:
@Testpublic void testArrayEquals() { String[] a = new String[]{"123"}; String[] b = new String[]{"123"}; System.out.println(ObjectUtils.nullSafeEquals(a, b));}
這個例子的執行結果返回的是true。
如果想要快速獲取某個對象十六進制的hashCode,則可以調用getIdentityHexString方法。
例如:
@Testpublic void testIdentityHex() { String a = "123"; System.out.println(ObjectUtils.getIdentityHexString(a));}
執行結果:2925bf5b
Spring的org.springframework.util包下的ClassUtils類,它里面有很多讓我們驚喜的功能。
它里面包含了類和對象相關的很多非常實用的方法。
如果你想獲取某個對象的所有接口,可以使用ClassUtils的getAllInterfaces方法。例如:
Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());
如果你想獲取某個類的包名,可以使用ClassUtils的getPackageName方法。例如:
String packageName = ClassUtils.getPackageName(User.class);System.out.println(packageName);
如果你想判斷某個類是否內部類,可以使用ClassUtils的isInnerClass方法。例如:
System.out.println(ClassUtils.isInnerClass(User.class));
如果你想判斷對象是否代理對象,可以使用ClassUtils的isCglibProxy方法。例如:
System.out.println(ClassUtils.isCglibProxy(new User()));
ClassUtils還有很多有用的方法,等待著你去發掘。感興趣的朋友,可以看看下面內容:
Spring給我們提供了一個JavaBean的工具類,它在org.springframework.beans包下面,它的名字叫做:BeanUtils
。
讓我們一起看看這個工具可以帶給我們哪些驚喜。
曾幾何時,你有沒有這樣的需求:把某個對象中的所有屬性,都拷貝到另外一個對象中。這時就能使用BeanUtils的copyProperties方法。例如:
User user1 = new User();user1.setId(1L);user1.setName("蘇三說技術");user1.setAddress("成都");User user2 = new User();BeanUtils.copyProperties(user1, user2);System.out.println(user2);
如果你想通過反射實例化一個類的對象,可以使用BeanUtils的instantiateClass方法。例如:
User user = BeanUtils.instantiateClass(User.class);System.out.println(user);
如果你想獲取某個類的指定方法,可以使用BeanUtils的findDeclaredMethod方法。例如:
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");System.out.println(declaredMethod.getName());
如果你想獲取某個方法的參數,可以使用BeanUtils的findPropertyForMethod方法。例如:
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");PropertyDescriptor propertyForMethod = BeanUtils.findPropertyForMethod(declaredMethod);System.out.println(propertyForMethod.getName());
如果你對BeanUtils比較感興趣,可以看看下面內容:
有時候,我們需要在項目中使用反射功能,如果使用最原始的方法來開發,代碼量會非常多,而且很麻煩,它需要處理一大堆異常以及訪問權限等問題。
好消息是Spring給我們提供了一個ReflectionUtils工具,它在org.springframework.util包下面。
如果你想獲取某個類的某個方法,可以使用ReflectionUtils類的findMethod方法。例如:
Method method = ReflectionUtils.findMethod(User.class, "getId");
如果你想獲取某個類的某個字段,可以使用ReflectionUtils類的findField方法。例如:
Field field = ReflectionUtils.findField(User.class, "id");
如果你想通過反射調用某個方法,傳遞參數,可以使用ReflectionUtils類的invokeMethod方法。例如:
ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);
如果你想判斷某個字段是否常量,可以使用ReflectionUtils類的isPublicStaticFinal方法。例如:
Field field = ReflectionUtils.findField(User.class, "id");System.out.println(ReflectionUtils.isPublicStaticFinal(field));
如果你想判斷某個方法是否equals方法,可以使用ReflectionUtils類的isEqualsMethod方法。例如:
Method method = ReflectionUtils.findMethod(User.class, "getId");System.out.println(ReflectionUtils.isEqualsMethod(method));
當然這個類還有不少有趣的方法,感興趣的朋友,可以看看下面內容:
有時候,為了安全考慮,需要將參數只用base64編碼。
這時就能直接使用org.springframework.util包下的Base64Utils工具類。
它里面包含:encode和decode方法,用于對數據進行編碼和解碼。
例如:
String str = "abc";String encode = new String(Base64Utils.encode(str.getBytes()));System.out.println("編碼后:" + encode);try { String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8"); System.out.println("解碼:" + decode);} catch (UnsupportedEncodingException e) { e.printStackTrace();}
執行結果:
編碼后:YWJj解碼后:abc
有時候,我們需要把數據進行序列化和反序列化處理。
傳統的做法是某個類實現Serializable接口,然后重新它的writeObject和readObject方法。
但如果使用org.springframework.util包下的SerializationUtils
工具類,能更輕松實現序列化和反序列化功能。
例如:
Map<String, String> map = Maps.newHashMap();map.put("a", "1");map.put("b", "2");map.put("c", "3");byte[] serialize = SerializationUtils.serialize(map);Object deserialize = SerializationUtils.deserialize(serialize);System.out.println(deserialize);
很多時候,我們會在代碼中定義http的返回碼,比如:接口正常返回200,異常返回500,接口找不到返回404,接口不可用返回502等。
private int SUCCESS_CODE = 200;private int ERROR_CODE = 500;private int NOT_FOUND_CODE = 404;
其實org.springframework.http包下的HttpStatus枚舉,或者org.apache.http包下的HttpStatus接口,已經把常用的http返回碼給我們定義好了,直接拿來用就可以了,真的不用再重復定義了。
有時候,用戶輸入的內容中包含了一些特殊的標簽,比如<,如果不錯處理程序可能會報錯。
而且為了安全性,對用戶輸入的特色字符,也需要做轉義,防止一些SQL注入,或者XSS攻擊等。
其實Spring給我們提供了一個專門處理html的工具:HtmlUtils,我們可以直接用它來做轉義,使用起來非常方便。
例如:
@Testpublic void testHtml() { String specialStr = "<div id=/"testDiv/">test1;test2</div>"; String str1 = HtmlUtils.htmlEscape(specialStr); System.out.println(str1);}
執行結果:<div id="testDiv">test1;test2</div>。
本文鏈接:http://www.www897cc.com/showinfo-26-70402-0.html別瞎寫工具類了,Spring自帶的不香嗎?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com