Object to Map 转换的三种方法
就是把对象以及其对应的属性名 和属性值, 映射到一个Map中
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
publicclass ObjectToMap {
publicstaticvoid main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
TestObject o = new TestObject();
o.setCity("beijing");
o.setName("bj");
o.setOrder("ASC");
ObjectToMap objectToMap = new ObjectToMap();
System.out.println("=========== Invoke objectToMapViaBeanInfo ===========");
objectToMap.objectToMapViaBeanInfo(o);
System.out.println("=========== Invoke objectToMapViaFields ===========");
objectToMap.objectToMapViaFields(o);
System.out.println("=========== Invoke objectToMapViaApacheTools ===========");
objectToMapViaApacheTools(o);
}
/**
if (reader == null reader.invoke(o) == null) {
continue;
}
//默认继承Object类的属性,过滤掉
if (pd.getName().equalsIgnoreCase("class")) {
continue;
}
result.put(pd.getName(), reader.invoke(o));
}
for (String key : result.keySet()) {
System.out.println("Key:" + key + ";Value:" + result.get(key));
}
}
/**
if (field.get(o) == null) {
continue;
}
resMap.put(field.getName(), field.get(o));
}
printOut(resMap);
}
/**
--转自
该贴由hui.chen转至本版2015-7-30 15:23:15