This reflected obtain all the properties classes and superclasses

This reflected obtain all the properties classes and superclasses

  1. getFields () : get all the public (public) field of a class, including the parent class field.

  2. getDeclaredFields () : get all the fields declared in a class, which includes public, private and proteced, but does not include the stated fields of the parent class.

  3. Also similarly there getConstructors () and getDeclaredConstructors (), getMethods () and getDeclaredMethods (), which represent both the method for obtaining a class constructor.

So the question is, I want to get to the current class and all the attributes of the parent class , how to do?

    /**
     * 获取本类及其父类的属性的方法
     * @param clazz 当前类对象
     * @return 字段数组
     */
    private static Field[] getAllFields(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        return fieldList.toArray(fields);
    }

test:

    public static void main(String[] args) {
        Student student = new Student();
        student.setStuClass("18001");
        student.setStuNum("19800101");
        student.setName("Tom");
        student.setAge("20");

        Class<? extends Student> clazz = student.getClass();
        Field[] fields = getAllFields(clazz);
        for (Field field : fields) {
            System.out.println(field.getName());
        }
    }

】 【参考: https: //www.cnblogs.com/JackZed/p/6888668.html

Guess you like

Origin www.cnblogs.com/baijinqiang/p/12010493.html