欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用反射将对象转Map

程序员文章站 2022-05-30 21:53:24
...

 

//使用反射将对象转Map<String, String>
public class Object2Map {

 public static void main(String[] args) throws Exception{
  User user = new User();
  user.setName("zhangsan");
  user.setAge(20);
  user.setBirthday(new Date());
  
  Map<String, String> map = new HashMap<String, String>();
  Field[] fields = user.getClass().getDeclaredFields();
  for(Field f: fields){
//   System.out.println(f.getType()+f.getClass().getName());
   //对日期类型格式化
   if(f.getType().equals(java.util.Date.class)){
    Object dobj = getValue(user, f.getName());
    /*
    long time = ((Date)dobj).getTime();
    String val = new Date(time){
     public String toString(){
      return (this.getYear()+ 1900)+"-" + (this.getMonth() + 1) + "-" + this.getDate();
     }
    }.toString();
    */
    String val = date2str((Date)dobj);
    map.put(f.getName(), val);
    continue;
   }
   map.put(f.getName(), getValue(user, f.getName()).toString());
  }
  
  Set<Entry<String, String>> set = map.entrySet();
  for(Entry<String, String> e: set){
   System.out.println(e.getKey()+", "+ e.getValue());
  }
  
  
  
 }
 
 static Object getValue(Object o,String fieldName)throws Exception{
  String getMethod = "get" + Character.toUpperCase(fieldName.charAt(0))
   + fieldName.substring(1);
  Method m= o.getClass().getMethod(getMethod, new Class[]{});
  return m.invoke(o, new Object[]{});
 }
 
 static String date2str(Date d){
  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  return df.format(d);
 }

 static class User{
  private String name;
  private Integer age;
  private Date birthday;
  
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public Integer getAge() {
   return age;
  }
  public void setAge(Integer age) {
   this.age = age;
  }
  public Date getBirthday() {
   return birthday;
  }
  public void setBirthday(Date birthday) {
   this.birthday = birthday;
  }
 }
 
}

相关标签: java