Java通过反射将类转化成map

来源:互联网 发布:小学生计算机编程教材 编辑:程序博客网 时间:2024/06/05 17:00
public Map<String, Object> ClassToMap(Object t) {


Map<String, Object> map = new HashMap<String, Object>();


Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
String fieldName = field.getName();
// System.out.println(fieldName);


// 如果属性名称和属性一样
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);


Class tCls = t.getClass();
Method getMethod;
try {
getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});


// System.out.println(fieldName +" "+value);
map.put(fieldName, value);


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
0 0