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