Spring 工具类之基本元素判断

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

实际业务开发中偶尔会遇到判断一个对象是否为基本数据类型,除了我们自老老实实的自己写之外,也可以借助 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,这个又是什么东西呢?


下篇博文仔细撸一下它



相关文章
|
Java Spring
解决Spring工具类BeanUtils copyProperties方法复制null的问题
解决Spring工具类BeanUtils copyProperties方法复制null的问题
864 0
|
3月前
|
Java Spring
spring restTemplate 进行http请求的工具类封装
spring restTemplate 进行http请求的工具类封装
106 3
|
5月前
|
开发框架 Java 数据库
|
5月前
|
缓存 小程序 Java
别再造反射轮子了,Spring中ReflectionUtils 工具类,应有尽有!
ReflectionUtils是spring针对反射提供的工具类。
|
12月前
|
存储 NoSQL Java
Spring Boot 如何编写一个通用的 Redis 工具类
Spring Boot 如何编写一个通用的 Redis 工具类
359 0
Spring Boot 如何编写一个通用的 Redis 工具类
|
10月前
|
Java Apache Spring
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
97 0
|
12月前
|
Java Spring
【Spring】org.springframework.util.StringUtils工具类中commaDelimitedListToStringArray的使用
【Spring】org.springframework.util.StringUtils工具类中commaDelimitedListToStringArray的使用
59 0
|
Java Spring
动态获取spring管理的bean工具类
动态获取spring管理的bean工具类
148 0
|
消息中间件 JavaScript 小程序
别再自己瞎写工具类了,Spring Boot 内置工具类应有尽有, 建议收藏!!
别再自己瞎写工具类了,Spring Boot 内置工具类应有尽有, 建议收藏!!
|
Java 开发者 Spring
Spring断言工具类 “Assert” 的基本操作!
Spring断言工具类 “Assert” 的基本操作!
248 0
Spring断言工具类 “Assert” 的基本操作!
下一篇
无影云桌面