使用反射将对象转Map

 

//使用反射将对象转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;
  }
 }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值