Returns an array of Field objects reflecting all the fields declared by the class including the fields of the superclasses as well. - Java Reflection

Java examples for Reflection:Field

Description

Returns an array of Field objects reflecting all the fields declared by the class including the fields of the superclasses as well.

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        System.out.println(getDeclaredFieldsInLineage(clazz));
    }//from www.j  av a  2s . com

    /**
     * Returns an array of {@code Field} objects reflecting all the fields declared by the class including the fields of
     * the superclasses as well.
     * <p/>
     * This method matches the same kinds of fields that are returned by {@link Class#getDeclaredFields()} with the
     * exception that it includes fields inherited from the superclasses. This means public, protected, default
     * (package) access, and private fields AND fields of those types inherited from the superclasses.
     * <p/>
     * The returned list is partially ordered. Results from more derived classes show up earlier in the list. Within the
     * set of fields for the same class, however, the order is undefined.
     *
     * @param clazz the class
     * @return the array of {@code Field} objects representing all the declared fields of this class
     * @see Class#getDeclaredFields() for more details
     */
    public static List<Field> getDeclaredFieldsInLineage(Class<?> clazz) {
        List<Field> fields = new ArrayList<Field>(Arrays.asList(clazz
                .getDeclaredFields()));
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null && !superClass.equals(Object.class)) {
            fields.addAll(getDeclaredFieldsInLineage(superClass));
        }
        return fields;
    }
}

Related Tutorials