retrieve Constant Fields - Java Reflection

Java examples for Reflection:Field

Description

retrieve Constant Fields

Demo Code


//package com.java2s;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

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

public class Main {
    public static List<Field> retrieveConstantFields(final Class<?> clazz) {
        final List<Field> fields = new ArrayList<Field>();
        for (final Field field : retrieveAllFields(clazz)) {
            if (!isFieldToBeProvided(field)) {
                fields.add(field);// ww  w  .  ja va  2 s.c o m
            }
        }
        return fields;
    }

    public static List<Field> retrieveAllFields(final Class<?> clazz) {
        final List<Field> fields = new ArrayList<Field>();
        Class<?> currentClass = clazz;
        while (!Object.class.equals(currentClass)) {
            for (final Field field : currentClass.getDeclaredFields()) {
                fields.add(field);
            }
            currentClass = currentClass.getSuperclass();
        }
        return fields;
    }

    private static boolean isFieldToBeProvided(final Field field) {
        return !field.getName().startsWith("$")
                && !(Modifier.isStatic(field.getModifiers()) && Modifier
                        .isFinal(field.getModifiers()));
    }
}

Related Tutorials