0
点赞
收藏
分享

微信扫一扫

Java反射/常用操作

北邮郭大宝 2022-01-04 阅读 45

获取对象所有属性名和值

注意

  • 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;
    }
}
举报

相关推荐

0 条评论