Java Reflection Annotation getAnnotations(Method method)

Here you can find the source of getAnnotations(Method method)

Description

get Annotations

License

Apache License

Declaration

public static List<Annotation> getAnnotations(Method method) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import java.util.List;
import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static final Map<Method, List<Annotation>> methodAnnotationCache = new ConcurrentHashMap<>();

    public static <T extends Annotation> List<T> getAnnotations(Method method, Class<T> type) {
        return filterAnnotations(getAnnotations(method), type);
    }/*from  w ww.j  a v  a2  s .c  o m*/

    public static List<Annotation> getAnnotations(Method method) {
        if (methodAnnotationCache.containsKey(method)) {
            return methodAnnotationCache.get(method);
        }

        List<Annotation> annotations = Collections.unmodifiableList(Arrays.asList(method.getAnnotations()));
        methodAnnotationCache.put(method, annotations);

        return annotations;
    }

    public static <T extends Annotation> List<T> filterAnnotations(Collection<Annotation> annotations,
            Class<T> type) {
        List<T> result = new ArrayList<>();

        for (Annotation annotation : annotations) {
            if (type.isInstance(annotation)) {
                result.add(type.cast(annotation));
            }
        }

        return result;
    }
}

Related

  1. getAnnotations(final Class clazz, final Class annotation)
  2. getAnnotations(final Class clazz, final String fieldName)
  3. getAnnotations(Method method)
  4. getAnnotations(Method method)
  5. getAnnotations(Method method)
  6. getAnnotations(Object instance)
  7. getAnnotations(Set fields, Set methods)
  8. getAnnotationsOf(Class annoClass)
  9. getAnnotationsRecursive(Class clazz)