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