retrieve Annotated Fields - Java Reflection

Java examples for Reflection:Field

Description

retrieve Annotated Fields

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

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

public class Main {
    public static List<Field> retrieveAnnotatedFields(
            final Class<?> objectClass,
            final Class<? extends Annotation> annotationClass) {
        final List<Field> fields = new ArrayList<>();
        for (final Field field : retrieveAllFields(objectClass)) {
            final Annotation annotation = field
                    .getAnnotation(annotationClass);
            if (annotation != null
                    && annotation.annotationType().equals(annotationClass)) {
                fields.add(field);// w w  w  . j av a2 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;
    }
}

Related Tutorials