美文网首页
通过javabean调用对象的set方法

通过javabean调用对象的set方法

作者: 写java的逗比叫z1 | 来源:发表于2017-06-20 16:42 被阅读0次
  1. 通过javabean调用对象的set方法
  2. struts2 Ognl
  3. java反射机制完成List与List
  4. KVO本质
  5. lombok get/set 与 JavaBean get/se
  6. 对象方法和类方法
  7. 学习途中之类方法和对象方法
  8. OC重学第二天
  9. KVC KVO
  10. 【Java工具】之CollectionUtil类(八)
  11.  /**
         * 通过javabean调用对象的set方法
         *
         * @param object
         * @param propertyName
         * @param propertyValue
         * @Author zy
         */
        public static void setPropertyValue(Object object, String propertyName, Object propertyValue) throws Exception {
            if (object == null)
                throw new Exception("object 参数不能为空!");
            if (propertyName == null)
                throw new Exception("propertyName 参数不能为空!");
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    if (propertyName.equals(propertyDescriptor.getName())) {
                        if (propertyDescriptor.getPropertyType() == null ||
                                !propertyDescriptor.getPropertyType().equals(propertyValue.getClass())) {
                            throw new Exception("propertyValue 类型不匹配");
                        }
                        propertyDescriptor.getWriteMethod().invoke(object, propertyValue);
                        break;
                    }
                }
            } catch (Exception e) {
                throw e;
            }
        }
    

    相关文章