仅供参考
@Log4j
public class ObjectToMap {
/*简单Object转成map*/
public static Map<String,String> toMap(Object o){
Map<String,String> map=new HashMap<String, String>();
Field[] fields=().getDeclaredFields();
try {
for (int i=0;i<;i++) {
String name=fields[i].getName();
Field field=().getDeclaredField(name);
(true);
if (null!=field){
(name,(o).toString());
}
}
}catch(Exception e){
((),e);
}
return map;
}
/*复杂Object转成map*/
public static Map<String, Object> toObjectMap(Object object) {
Map<String, Object> map = new HashMap<String, Object>();
toMap((), object, map);
return map;
}
private static void toMap(Class<?> clazz, Object object, Map<String, Object> map) {
Method[] methods = ();
if (methods != null && > 0) {
for (Method method : methods) {
String mname = ();
if (("get") && ().length == 0) {
try {
String fieldName = (3, 4).toLowerCase() + (4);
if ("serialVersionUID".equals(fieldName)) {
continue;
} else if ("class".equals(fieldName)) {
continue;
}
Object fieldValue = (object, null);
if (fieldValue != null) {
(fieldName, fieldValue);
}
} catch (IllegalAccessException e) {
((),e);
} catch (InvocationTargetException e) {
((),e);
} catch (SecurityException e) {
((),e);
}
}
}
}
if (() != null) {
toMap((), object, map);
}
}
public static void main(String[] args)throws Exception {
Tests tests=new Tests(10,"zhangsan");
ObjectToMap om= new ObjectToMap();
Map<String,String> map= (tests);
(());
Map<String,Object> omap= (tests);
(());
}
}
class Tests{
private int age;
private String name;
public Tests(int age,String name) {
=age;
=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
= age;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
}