has Constant With Name - Java Reflection

Java examples for Reflection:Constructor

Description

has Constant With Name

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 boolean hasConstantWithName(final Class<?> clazz,
            final String fieldName) {
        for (final Field field : retrieveConstantFields(clazz)) {
            if (field.getName().equals(fieldName)) {
                return true;
            }//  w ww.  j ava 2 s  .c  o m
        }
        return false;
    }

    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);
            }
        }
        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