栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Java:内省

Java 更新时间:发布时间: 百科书网 趣学号

内省:将javabean中不管是公有地还是私有的,通过构造器,将其中的属性和方法拿出来使用.

底层原理:通过反射来实现.

通过BeanInfo来获取bean中的属性,方法,并操控

public void copybean(Map map, Object bean){
        try {
            //获取javabean
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(),Object.class);

            //获取所有属性
            PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors();

            //如果实体类中属性为空,则不做任何操作
            if (propertyDescriptor==null){
                return;
            }

            //遍历所有属性
            for (PropertyDescriptor p:propertyDescriptor) {
                //获取集合中属性的值
                String value = map.get(p.getName());

                //如果值为空或者为空字符串,则跳过当前循环进入下一次
                if (value==null||value.trim().equals("")){
                    continue;
                }

                //将所有属性set到bean中
                //为p设置set方法,getReadMethod()为声明的变量设置get方法
                Method writeMethod = p.getWriteMethod();
                System.out.println(p.getPropertyType().getName());
                System.out.println(Integer.class.getName());

                //获取属性的类型
                if (p.getPropertyType().getName().equals("int")){
                    //判断类型是否为Integer类型
                    writeMethod.invoke(bean,Integer.parseInt(value));
                }else if (p.getPropertyType().getName().equals(Double.class.getName())){
                    //判断类型是否为Double类型
                    writeMethod.invoke(bean,Double.valueOf(value));
                }else {
                    writeMethod.invoke(bean,value);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/275917.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号