使用反射将对象转Map_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 使用反射将对象转Map

使用反射将对象转Map

 2018/5/27 18:11:54  zw7534313  程序员俱乐部  我要评论(0)
  • 摘要://使用反射将对象转Map<String,String>publicclassObject2Map{publicstaticvoidmain(String[]args)throwsException{Useruser=newUser();user.setName("zhangsan");user.setAge(20);user.setBirthday(newDate());Map<String,String>map=newHashMap<String
  • 标签:使用 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;
??}
?}
?
}

上一篇: 设计模式之责任链 下一篇: 没有下一篇了!
发表评论
用户名: 匿名