1.[代码][Java]代码
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ConventionUtil {
public static Map beanToMap(Object bean) {
Map resultMap = new HashMap();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if (propertyDescriptors != null && propertyDescriptors.length > 0) {
for (PropertyDescriptor descriptor : propertyDescriptors) {
String propertyName = descriptor.getName();
if ("class".equals(propertyName)) {
continue;
}
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
resultMap.put(propertyName, result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
}