Spring 工具類之基本元素判斷

Spring 工具類之基本元素判斷

實際業務開發中偶爾會遇到判斷一個對象是否爲基本數據類型,除了我們自老老實實的自己寫之外,也可以藉助 Spring 的 BeanUtils 工具類來實現

// Java基本數據類型及包裝類型判斷
org.springframework.util.ClassUtils#isPrimitiveOrWrapper

// 擴展的基本類型判斷
org.springframework.beans.BeanUtils#isSimpleProperty

這兩個工具類的實現都比較清晰,源碼看一下,可能比我們自己實現要優雅很多

基本類型判定:ClassUtils

public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
	Assert.notNull(clazz, "Class must not be null");
	return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}

注意:非包裝類型,直接使用class.isPrimitive() 原生的 jdk 方法即可

包裝類型,則實現使用 Map 來初始化判定


private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(8);

static {
	primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
	primitiveWrapperTypeMap.put(Byte.class, byte.class);
	primitiveWrapperTypeMap.put(Character.class, char.class);
	primitiveWrapperTypeMap.put(Double.class, double.class);
	primitiveWrapperTypeMap.put(Float.class, float.class);
	primitiveWrapperTypeMap.put(Integer.class, int.class);
	primitiveWrapperTypeMap.put(Long.class, long.class);
	primitiveWrapperTypeMap.put(Short.class, short.class);
	primitiveWrapperTypeMap.put(Void.class, void.class);
}


public static boolean isPrimitiveWrapper(Class<?> clazz) {
	Assert.notNull(clazz, "Class must not be null");
	return primitiveWrapperTypeMap.containsKey(clazz);
}

這裏非常有意思的一個點是這個 Map 容器選擇了IdentityHashMap,這個又是什麼東西呢?

下篇博文仔細擼一下它

II. 其他

1. 一灰灰 Bloghttps://liuyueyi.github.io/hexblog

一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛

2. 聲明

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激

3. 掃描關注

一灰灰 blog

QrCode

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