find Annotations In Method - Java java.lang.annotation

Java examples for java.lang.annotation:Method Annotation

Description

find Annotations In Method

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
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(findAnnotationsInMethod(clazz, annotationClass));
    }//from  w w w  .  j  av  a 2 s. c  om

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

        for (Method method : clazz.getDeclaredMethods()) {
            T anno = method.getAnnotation(annotationClass);
            if (anno != null) {
                answer.add(anno);
            }
        }

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

        return answer;
    }

    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