java Object类型转Map

仅供参考

@Log4j
public class ObjectToMap {
/*简单Object转成map*/
public static Map toMap(Object o){
Map map=new HashMap();
Field[] fields=o.getClass().getDeclaredFields();
try {
for (int i=0;i String name=fields[i].getName();
Field field=o.getClass().getDeclaredField(name);
field.setAccessible(true);
if (null!=field){
map.put(name,field.get(o).toString());
}
}
}catch(Exception e){
log.error(e.getMessage(),e);
}
return map;
}
/*复杂Object转成map*/
public static Map toObjectMap(Object object) {
Map map = new HashMap();
toMap(object.getClass(), object, map);
return map;
}
private static void toMap(Class<> clazz, Object object, Map map) {
Method[] methods = clazz.getDeclaredMethods();
if (methods != null && methods.length > 0) {
for (Method method : methods) {
String mname = method.getName();
if (mname.startsWith(“get”) && method.getParameterTypes().length == 0) {
try {
String fieldName = mname.substring(3, 4).toLowerCase() + mname.substring(4);
if (“serialVersionUID”.equals(fieldName)) {
continue;
} else if (“class”.equals(fieldName)) {
continue;
}
Object fieldValue = method.invoke(object, null);
if (fieldValue != null) {
map.put(fieldName, fieldValue);
}
} catch (IllegalAccessException e) {
log.info(e.getMessage(),e);

} catch (InvocationTargetException e) {
log.info(e.getMessage(),e);
} catch (SecurityException e) {
log.error(e.getMessage(),e);
}
}
}
}
if (clazz.getSuperclass() != null) {
toMap(clazz.getSuperclass(), object, map);
}
}

public static void main(String[] args)throws Exception {
Tests tests=new Tests(10,“zhangsan”);
ObjectToMap om= new ObjectToMap();
Map map= om.toMap(tests);
System.out.println(map.toString());
Map omap= om.toObjectMap(tests);
System.out.println(omap.toString());
}

}
class Tests{
private int age;
private String name;

public Tests(int age,String name) {
this.age=age;
this.name=name;
}
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

你可能感兴趣的:(java,java,后端)