日期:2014-05-20  浏览次数:20756 次

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

------解决方案--------------------
可以考虑使用java的反射机制
------解决方案--------------------
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;
  }
}
------解决方案--------------------
楼上正解
------解决方案--------------------
就是java的反射