一個很簡單的工具類,實體bean轉換成map
簡單的實體類:
package cn.ibm.com.mytest;
public class Human {
private Integer hid;
private String hname;
public Integer getHid() {
return hid;
}
public void setHid(Integer hid) {
this.hid = hid;
}
public String getHname() {
return hname;
}
public void setHname(String hname) {
this.hname = hname;
}
}
主要的內容:
package cn.ibm.com.mytest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DomainToMapUtil {
private static Log log = LogFactory.getLog(TestMany.class);
public static Map domainToMap(Class clazz,Object obj) throws Exception{
Map map = new HashMap();
Field[] fields = clazz.getDeclaredFields();
for(int i=0;i<fields.length;i++){
Field f = fields[i];
f.setAccessible(true);
String key = f.getName();
char[] chs = key.toCharArray();
StringBuilder strMethod = new StringBuilder("get");
strMethod.append((chs[0]+"").toUpperCase());
for(int j=1;j<chs.length;j++){
strMethod.append(chs[j]);
}
Method method = clazz.getDeclaredMethod(strMethod.toString(), null);
map.put(key, method.invoke(obj, null));
}
return map;
}
}
測試:
package cn.ibm.com.mytest;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
public class TestMany {
private static Log log = LogFactory.getLog(TestMany.class);
@Test
public void dotest() throws Exception{
Human h = new Human();
h.setHid(123);
h.setHname("name");
Class c = h.getClass();
Map<String, Object> maps = DomainToMapUtil.domainToMap(c,h);
log.info(maps);
}
}