• Spring 工具类之基本元素判断


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

    3. 扫描关注

    一灰灰 blog

    QrCode

  • 相关阅读:
    css 标签 清除浮动
    css 标签 垂直居中
    getResource().getPath()返回的路径空格变成了 %20
    css3颜色渐变
    网页动画结束判断事件
    手机端js事件支持(event)
    手机端js实现滑块推动
    手机端js模拟长按事件(代码仿照jQuery)
    基于SOA架构---ServiceProxy定义
    对SSL加密通信安全的理解
  • 原文地址:https://www.cnblogs.com/yihuihui/p/14290068.html
Copyright © 2020-2023  润新知