java 实体对象转Map公共类

 

java 实体对象转Map公共类

 

 

 

 

package org.kxtkx.portal.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.kxtkx.portal.user.Admin;
/**
 * 
 * @author <a href="mailto:wangc@kxtkx.com">王成</a> 
 * @created in 2011-6-24 - 下午02:58:50
 * 本类说明:对象转Map
 */
public class ObjAnalysis {
 
 public static Map ConvertObjToMap(Object obj){
  Map<String,Object> reMap = new HashMap<String,Object>();
  if (obj == null) 
   return null;
  Field[] fields = obj.getClass().getDeclaredFields();
  try {
   for(int i=0;i<fields.length;i++){
    try {
     Field f = obj.getClass().getDeclaredField(fields[i].getName());
     f.setAccessible(true);
           Object o = f.get(obj);
           reMap.put(fields[i].getName(), o);
    } catch (NoSuchFieldException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IllegalArgumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IllegalAccessException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
  return reMap;
 }
 
 public static void main(String[] args) {
  Admin a = new Admin();
  a.setCPassword("123456");
  a.setCUsername("王成");
  Map m = ConvertObjToMap(a);
  System.out.println(m);
 }
}

 

 

posted @ 2016-08-03 10:40  程序猿网友666  阅读(17975)  评论(0编辑  收藏  举报