关于java:Spring-工具类之基本元素判断

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理