直接看代码:
public class ConvertUtil {
private static final Logger logger = Logger.getLogger(ConvertUtil.class);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OrgResponse resp = new OrgResponse();
resp.setAccountNumber("12346");
resp.setCustomerID("5566");
resp.setPassword("hello1sa");
// Map<String, Object> resultMap = ConvertUtil.convertBeanToMap(resp);
// System.out.println("convertSimpleBeanToMap result: ");
// for (Entry<String, Object> en : resultMap.entrySet()) {
// logger.info(en.getKey() + ": " + en.getValue());
// }
//
// OrgResponse newRes = convertMapToBean(resultMap, resp);
// System.out.println("convertMapToSimpleBean result: ");
// logger.info(newRes.getAccountNumber()+", " + newRes.getCustomerID() + ", "
// + newRes.getPassword());
}
/**
* Use Reflection to convert Map to java Bean, Ignore the upper/lower case of attributes letters.
*
*/
public static <T> T convertMapToBean(Map<String, Object> map, T t) {
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> et : entrySet) {
String key = et.getKey().toLowerCase(); // convert to lower case
Object value = et.getValue();
List<Method> list = new ArrayList<Method>();
getObjSetMethodsWithExtends(t.getClass(), list);
for (int i = 0; i < list.size(); i++) {
String name = list.get(i).getName();// method name
if (!changeStrToSetMethodNames(key).equalsIgnoreCase(name))
continue;
try {
list.get(i).invoke(t, value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
break;
}
}
return t;
}
/**
* Use Reflection to convert java Bean to Map
*
*/
public static <T> Map<String, Object> convertBeanToMap(T t) {
Map<String, Object> map = new HashMap<String, Object>();
Class cls = t.getClass();
Field[] fieldlist = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field f = fieldlist[i];
String name = f.getName();
Class<?> cs = f.getType();
try {
String methodNme = changeStrToGetMethodNames(name);
Method meth = null;
Method[] mds = cls.getDeclaredMethods();
for (int j = 0; j < mds.length; j++) {
if (mds[j].getName().equals(methodNme)) {
meth = cls.getMethod(methodNme);
Object rtcs = meth.invoke(t, null);
map.put(name, rtcs);
break;
}
}
if (meth == null) {
logger.info("Can not find the method " + methodNme + " in class " + t.getClass().getName());
}
} catch (SecurityException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
}
}
return map;
}
private static String changeStrToSetMethodNames(String str) {
if (str == null || "".equals(str.trim()))
return null;
char firstChar = str.toCharArray()[0];
String upstr = String.valueOf(firstChar).toUpperCase();
return "set" + upstr + str.substring(1);
}
private static String changeStrToGetMethodNames(String str) {
if (str == null || "".equals(str.trim()))
return null;
char firstChar = str.toCharArray()[0];
String upstr = String.valueOf(firstChar).toUpperCase();
return "get" + upstr + str.substring(1);
}
private static void getObjSetMethodsWithExtends(Class<?> cls, List<Method> list) {
if (cls.equals(Object.class)) {
return;
}
Method[] mds = cls.getDeclaredMethods();
for (int i = 0; i < mds.length; i++) {
if (!mds[i].getName().startsWith("set"))
continue;
list.add(mds[i]);
}
getObjSetMethodsWithExtends(cls.getSuperclass(), list);
}
}