/**
* java对象转map
* @param obj
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static Map obj2Map(Object obj) throws Exception {
Map result = new HashMap();
//一些基础引用类型
List baseType = Arrays.asList(new String[]{
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Character",
"java.lang.Double",
"java.lang.Float",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Short",
"java.lang.String",
"java.math.BigDecimal"
});
Class> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for(int i = 0,len = fields.length; i
fields[i].setAccessible(true);
if(baseType.contains(fields[i].getType().getName())) {
//类型判断,基本类型判断、基础引用类型判断、数组判断
result.put(fields[i].getName(), fields[i].get(obj));
} else if(isBaseArray(fields[i].get(obj))) {
//数组
result.put(fields[i].getName(), fields[i].get(obj));
} else {
Object value = fields[i].get(obj);
result.put(fields[i].getName(), obj2Map(value));
}
}
return result;
}
private static Boolean isBaseArray(Object obj) {
if(obj instanceof Integer[] || obj instanceof int[]) {
return true;
}
if(obj instanceof Boolean[] || obj instanceof boolean[]) {
return true;
}
if(obj instanceof Byte[] || obj instanceof byte[]) {
return true;
}
if(obj instanceof Character[] || obj instanceof char[]) {
return true;
}
if(obj instanceof Double[] || obj instanceof double[]) {
return true;
}
if(obj instanceof Float[] || obj instanceof float[]) {
return true;
}
if(obj instanceof Long[] || obj instanceof long[]) {
return true;
}
if(obj instanceof Short[] || obj instanceof short[]) {
return true;
}
if(obj instanceof String[]) {
return true;
}
if(obj instanceof BigDecimal[]) {
return true;
}
if("java.util.ArrayList".equals(obj.getClass().getName())) {
return true;
}
return false;
}