关于 Introspector 内省器在项目中的简单应用

最近项目中有这么一个需求, 就是在对象返回时候,针对某些属性,的特定值, 进行处理, 本来想写注解, 但赶时间,就随便用了 Introspector 来反射处理

内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。

JDK内省类库:  

PropertyDescriptor类:

  PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:

      1. getPropertyType(),获得属性的Class对象;
      2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
      3. hashCode(),获取对象的哈希值;
      4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
      5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。

    public static <T> T nullifyBpsProperties(T object) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String propertyName = propertyDescriptor.getName();
                if (propertyName.endsWith("Bps")) {
                    Method readMethod = propertyDescriptor.getReadMethod();
                    Method writeMethod = propertyDescriptor.getWriteMethod();

                    if (readMethod != null && writeMethod != null) {
                        Object propertyValue = readMethod.invoke(object);
                        if (propertyValue instanceof Integer && (Integer) propertyValue == -1) {
                            writeMethod.invoke(object, (Object) null);
                        }
                        if (propertyValue instanceof BigDecimal && ((BigDecimal) propertyValue).compareTo(new BigDecimal(-1)) == 0) {
                            writeMethod.invoke(object, (Object) null);
                        }
                    }
                }
            }

        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            log.error("nullifyBpsProperties error,e=",e);
        }

        return object;
    }

顺便再提一下其他方式

BeanUtils的简单使用 

BeanUtils.setProperty(userInfo, "userName", "huang");

BeanUtils.getProperty(userInfo, "userName");

PropertyUtils的简单使用

PropertyUtils.setProperty(userInfo, "age", 24);

PropertyUtils.getProperty(userInfo, "age");

BeanUtils的特点:
    1). 对基本数据类型的属性的操作:在WEB开发、使用中,录入和显示时,值会被转换成字符串,但底层运算用的是基本类型,这些类型转到动作由BeanUtils自动完成。
    2). 对引用数据类型的属性的操作:首先在类中必须有对象,不能是null,例如,private Date birthday=new Date();。操作的是对象的属性而不是整个对象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111); 

PropertyUtils类和BeanUtils不同在于,运行getProperty、setProperty操作时,没有类型转换,使用属性的原有类型或者包装类。由于age属性的数据类型是int,所以方法PropertyUtils.setProperty(userInfo, "age", "24")会爆出数据类型不匹配,无法将值赋给属性。

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值