如题,将map对象转换成指定pojo对象
在线等

解决方案 »

  1.   

    那你的 Map 里面放了些什么?键是 POJO 的属性,值是 POJO 的属性值?
      

  2.   


    key是 POJO 的属性,value是 POJO 的属性值
      

  3.   

    package test;import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.util.HashMap;
    import java.util.Map;public class Test {  public static void main(String[] args) throws ClassNotFoundException, 
          InstantiationException, IllegalAccessException, IllegalArgumentException,
          InvocationTargetException, SecurityException, NoSuchFieldException {    Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "abc");
        map.put("age", 20);    Student stu = new Student();
        
        Class clazz = Class.forName("test.Student");      for (Map.Entry<String, Object> entry : map.entrySet()) {
          Field field = clazz.getDeclaredField(entry.getKey());
          field.setAccessible(true);
          field.set(stu, entry.getValue());
        }    System.out.println(stu.getName());
        System.out.println(stu.getAge());
      }
    }class Student {
      private String name;
      private int age;
      public int getAge() {
        return age;
      }
      public void setAge(int age) {
        this.age = age;
      }
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
    }
      

  4.   

    /**
     * 
     * 标题:中石油集团公司生产管理系统
     * 
     * 专业:录井专业
     * 
     * 公司: 荆鹏
     * 
     * 作者:宋腾,2007-8-20
     * 
     * 描述:对该类所实现的功能做大致的描述
     * 
     * 说明: 需要特别注明的信息在此描述
     */
    public static Object mapToPojo(Map map, Object  pojo) throws Exception {


    // 获得对象的类型
    Class classType = pojo.getClass();
    // 获得对象的所有属性
    Field fields[] = classType.getDeclaredFields();
    // Field mapFields[] = null;
    Iterator keyValuePairs = map.entrySet().iterator();
    for (int i = 0; i < map.size(); i++) {
    Map.Entry entry = (Map.Entry) keyValuePairs.next();
    String key = (String) entry.getKey();
    String value = (String) entry.getValue();
    String firstKey = key.substring(0, 1).toUpperCase();
    // 获得和属性对应的getXXX()方法的名字
    String getMethodName = "set" + firstKey + key.substring(1);
    // 获得和属性对应的getXXX()方法
    Class[] cargs = new Class[1]; 
    String realArgs = value; 
    Integer in = new Integer(2);
    cargs[0] = realArgs.getClass();
    Method getMethod = classType.getMethod(getMethodName,
    cargs);
    // 调用原对象的getXXX()方法
    Object test = getMethod.invoke(pojo, value);
    System.out.println(test);
    }
    return pojo;
    }
      

  5.   

    最简单的办法是用 BeanUtils.populate(entity, map);它可以将属性直接赋值给pojo