find Annotations In Field - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

find Annotations In Field

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 void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Class annotationClass = String.class;
        System.out.println(findAnnotationsInField(clazz, annotationClass));
    }/*from w ww  . j a  v a  2  s .co m*/

    public static <T extends Annotation> List<T> findAnnotationsInField(
            Class<?> clazz, Class<T> annotationClass) {
        List<T> answer = new ArrayList<T>();

        for (Field field : clazz.getDeclaredFields()) {
            T anno = field.getAnnotation(annotationClass);
            if (anno != null) {
                answer.add(anno);
            }
        }

        if (clazz.getSuperclass() != null) {
            answer.addAll(findAnnotationsInField(clazz.getSuperclass(),
                    annotationClass));
        }

        return answer;
    }
}

Related Tutorials