Search code examples
javareflectioninheritanceprivate-members

Access to private inherited fields via reflection in Java


I found a way to get inherited members via class.getDeclaredFields(); and acces to private members via class.getFields() But i'm looking for private inherited fields. How can i achieve this?


Solution

  • In fact i use a complex type hierachy so you solution is not complete. I need to make a recursive call to get all the private inherited fields. Here is my solution

     /**
     * Return the set of fields declared at all level of class hierachy
     */
    public static List<Field> getAllFields(Class<?> clazz) {
        return getAllFieldsRec(clazz, new ArrayList<>());
    }
    
    private static List<Field> getAllFieldsRec(Class<?> clazz, List<Field> list) {
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            getAllFieldsRec(superClazz, list);
        }
        list.addAll(Arrays.asList(clazz.getDeclaredFields()));
        return list;
    }