java中将bean转为map
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class MyBeanUtil {
/**
* 将bean转换成map
* @Description:
*/
public static Map beanToMap(Object o) {
if (o == null) {
return null;
}
Map map = new HashMap();
BeanInfo info = null;
try {
info = Introspector.getBeanInfo(o.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
Method reader = pd.getReadMethod();
if (reader != null && !"class".equals(pd.getName())) {
try {
map.put(pd.getName(), reader.invoke(o));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return map;
}
}