【Java】Spring 工具类之基本元素判断

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

// Java基本数据类型及包装类型判断

org.springframework.util.ClassUtils#isPrimitiveOrWrapper

// 扩展的基本类型判断

org.springframework.beans.BeanUtils#isSimpleProperty

<!-- more -->

这两个工具类的实现都比较清晰,源码看一下,可能比我们自己实现要优雅很多

基本类型判定: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. 一灰灰 Blog: https://liuyueyi.github.io/he...

一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

2. 声明

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

  • 微博地址: 小灰灰 Blog

  • QQ: 一灰灰/3302797840

3. 扫描关注

一灰灰 blog

【Java】Spring 工具类之基本元素判断

以上是 【Java】Spring 工具类之基本元素判断 的全部内容, 来源链接: utcz.com/a/101294.html

回到顶部