首页 > 其他 > 详细

day27(反射之内省机制实现BeanUtils)

时间:2017-10-16 20:54:54      阅读:118      评论:0      收藏:0      [点我收藏+]

 

    使用内省方式来实现beanUtils往对象里面存值

public class BeanInfoUtil2 {
	public static void setPropertyByIntrospector(Object userInfo,  
            Map<String,Object> map) throws Exception {  
			//map  key=name  value=value
        BeanInfo beanInfo = Introspector.getBeanInfo(userInfo.getClass());  
        PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();  
        if (proDescrtptors != null && proDescrtptors.length > 0) {  
            for (PropertyDescriptor propDesc : proDescrtptors) {  
            	Method method = propDesc.getWriteMethod();
            	if (null==method) {
					continue;
				}
                for (String keys : map.keySet()) {
					if (method.getName().equals("set"+keys)) {
						method.invoke(userInfo, map.get(keys));
					}
				}
            }  
        }  
    }  
}

    测试类

                Student s=new Student();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("Name", "张三");
		map.put("Age", 15);
		BeanInfoUtil2.setPropertyByIntrospector(s, map);
		System.out.println(s.getName());
		System.out.println(s.getAge());        

  

      

    

 

day27(反射之内省机制实现BeanUtils)

原文:http://www.cnblogs.com/fjkgrbk/p/introspection_.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!