Spring 工具类之基本元素判断

Spring 工具类之基本元素判断

实际业务开发中偶尔会遇到判断一个对象是否为基本数据类型,除了咱们自老老实实的本身写以外,也能够借助 Spring 的 BeanUtils 工具类来实现java

// Java基本数据类型及包装类型判断
org.springframework.util.ClassUtils#isPrimitiveOrWrapper

// 扩展的基本类型判断
org.springframework.beans.BeanUtils#isSimpleProperty

<!-- more -->git

这两个工具类的实现都比较清晰,源码看一下,可能比咱们本身实现要优雅不少github

基本类型断定:ClassUtilsspring

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

注意:非包装类型,直接使用class.isPrimitive() 原生的 jdk 方法便可app

包装类型,则实现使用 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,这个又是什么东西呢?学习

下篇博文仔细撸一下它spa

II. 其余

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

一灰灰的我的博客,记录全部学习和工做中的博文,欢迎你们前去逛逛code

2. 声明

尽信书则不如,以上内容,纯属一家之言,因我的能力有限,不免有疏漏和错误之处,如发现 bug 或者有更好的建议,欢迎批评指正,不吝感激对象

3. 扫描关注

一灰灰 blog

QrCode

相关文章
相关标签/搜索