find All Fields from a class via reflection - Java Reflection

Java examples for Reflection:Field

Description

find All Fields from a class via reflection

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(findAllFields(clazz));
    }/*from   w w w. j av  a 2 s .c om*/

    public static List<Field> findAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<Field>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
        }
        return fields;
    }
}

Related Tutorials