美文网首页码农日历JAVA随笔
Spring 工具类之基本元素判断

Spring 工具类之基本元素判断

作者: 一灰灰blog | 来源:发表于2021-01-17 20:32 被阅读0次

    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 或者有更好的建议,欢迎批评指正,不吝感激

    欢迎关注微信公众号,大量技术干活分享

    • 一灰灰blog
    • 一灰灰blog
    • 一灰灰blog

    相关文章

      网友评论

        本文标题:Spring 工具类之基本元素判断

        本文链接:https://www.haomeiwen.com/subject/qgjzaktx.html