Adds all fields with the specified Annotation of class clazz and its superclasses to all Fields - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

Adds all fields with the specified Annotation of class clazz and its superclasses to all Fields

Demo Code

/*//  w w  w .j  a v  a2s.c o  m
 * Copyright 2002-2006,2009 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.lang.annotation.Annotation;

import java.lang.reflect.Field;

import java.util.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class annotationClass = String.class;
        Class clazz = String.class;
        List allFields = java.util.Arrays.asList("asdf", "java2s.com");
        addAllFields(annotationClass, clazz, allFields);
    }

    /**
     * Adds all fields with the specified Annotation of class clazz and its superclasses to allFields
     *
     * @param annotationClass
     * @param clazz
     * @param allFields
     */
    public static void addAllFields(Class annotationClass, Class clazz,
            List<Field> allFields) {

        if (clazz == null) {
            return;
        }

        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            Annotation ann = field.getAnnotation(annotationClass);
            if (ann != null) {
                allFields.add(field);
            }
        }
        addAllFields(annotationClass, clazz.getSuperclass(), allFields);
    }
}

Related Tutorials