获取对象所有属性名和值
注意
- getter和setter方法的命名要规范
- PropertyDescriptor(jdk1.8):要求setter返回值为void
- lombok的@Accessors(chain = true):链式调用注解,setter方法返回对象本身
Main
public class Main {
public static void main(String[] args) throws Exception {
Student xcrj = new Student();
xcrj.setName("xcrj");
Map<String, Object> nameValueMap = getObjFieldNameValue(xcrj);
}
public static Map<String, Object> getObjFieldNameValue(Object obj) throws Exception {
Class clazz = obj.getClass();
Map<String, Object> map = new HashMap<>();
// getDeclaredFields
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
// PropertyDescriptor
PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
// getMethod
Method getMethod = pd.getReadMethod();
Object value = getMethod.invoke(obj);
map.put(fieldName, value);
}
return map;
}
}