map对象转实体对象

来源:互联网 发布:智盟软件电话 编辑:程序博客网 时间:2024/05/20 03:06
可用于从数据库中取出的map转换为实体通用方法
@Testpublic void testMapToEntity(){Map<String ,Object> map = new HashMap<String,Object>();map.put("name", "球球");map.put("age", 18);try {User user = (User)convertMap(User.class,map);System.out.println("name:"+user.getName()+"\nage:"+user.getAge());} catch (Exception e) {e.printStackTrace();}}
/**map转实体对象 * @param type:需要转换的对象 * @param map:参数为实体对象属性**/public Object convertMap(Class type,Map map) throws Exception{//创建JavaBean对象Object obj = type.newInstance();//获取类属性BeanInfo beanInfo = Introspector.getBeanInfo(type);//所有属性数组PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for(PropertyDescriptor propertyDescriptor : propertyDescriptors){//获取属性名String propertyName = propertyDescriptor.getName();if(map.get(propertyName)!=null){Object value = map.get(propertyName);//属性赋值propertyDescriptor.getWriteMethod().invoke(obj, value);}}return obj;}
class User {protected String name;protected Integer age;public void setName(String name){this.name = name;}public String getName(){return name;}public void setAge(Integer age){this.age = age;}public Integer getAge(){return age;}}