Java Reflection Field Find findFieldsAnnotatedWith(final Class type, final Class annotation)

Here you can find the source of findFieldsAnnotatedWith(final Class type, final Class annotation)

Description

find Fields Annotated With

License

Open Source License

Declaration

public static List<Field> findFieldsAnnotatedWith(final Class<?> type,
            final Class<? extends Annotation> annotation) 

Method Source Code


//package com.java2s;
/*// w  w w.j  a v  a 2  s  .c  om
 * @(#)ReflectUtils.java 2014?1?1? ????23:33:33
 *
 * Copyright (c) 2011-2014 Makersoft.org all rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 */

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

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

public class Main {
    public static List<Field> findFieldsAnnotatedWith(final Class<?> type,
            final Class<? extends Annotation> annotation) {
        List<Field> fields = new ArrayList<Field>();
        Class<?> klass = type;
        while (klass != null && klass != Object.class) { // need to iterated thought hierarchy in order to retrieve
                                                         // methods from above the current instance
                                                         // iterate though the list of methods declared in the class represented by klass
                                                         // variable, and add those annotated with the specified annotation
            final List<Field> allFields = new ArrayList<Field>(Arrays.asList(klass.getDeclaredFields()));
            for (final Field field : allFields) {
                if (annotation == null || field.isAnnotationPresent(annotation)) {
                    //                  Annotation annotInstance = method.getAnnotation(annotation);
                    // TODO process annotInstance
                    fields.add(field);
                }
            }
            // move to the upper class in the hierarchy in search for more fields
            klass = klass.getSuperclass();
        }
        return fields;
    }
}

Related

  1. findFieldRecursively(Class c, String fieldName)
  2. findFields(Class c, boolean allowTransient, int max, Iterable> fieldClassesToFind, Iterable> exceptClasses)
  3. findFields(Class type)
  4. findFields(final Class clazz, final Predicate filter)
  5. findFieldsAnnotatedWith(Class annotation, Class parentClass)
  6. findFieldsOfClass(Class target, Object o, String path, Logger log, Set done)
  7. findFieldToInject(Class target, String name, Class source)
  8. findFieldType(Field field, Class concreteClass)
  9. findFieldWithAnnotation(String fieldName, Class clazz, Class annotationType)