Java Reflection Annotation getAnnotations(Method method)

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

Description

Returns all of the Annotation s defined on the given Method .

License

Open Source License

Parameter

Parameter Description
method the Method

Return

the s

Declaration

public static List<Annotation> getAnnotations(Method method) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

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

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

    /**// w  ww .  jav  a2s.com
     * Returns all of the {@link Annotation}s defined on
     * the given {@link Method}.
     * @param method the {@link Method}
     * @return the {@link Annotation}s
     */
    public static List<Annotation> getAnnotations(Method method) {
        if (methodAnnotationCache.containsKey(method)) {
            return methodAnnotationCache.get(method);
        }
        List<Annotation> annotations = new ArrayList<Annotation>();
        for (Annotation a : method.getAnnotations()) {
            annotations.add(a);
        }
        annotations = Collections.unmodifiableList(annotations);
        methodAnnotationCache.put(method, annotations);
        return annotations;
    }

    /**
     * Returns {@link Annotation}s of the given type defined
     * on the given {@link Method}.
     * @param <T> the {@link Annotation} type
     * @param method the {@link Method}
     * @param type the type
     * @return the {@link Annotation}s
     */
    public static <T extends Annotation> List<T> getAnnotations(Method method, Class<T> type) {
        List<T> ret = new ArrayList<T>();
        for (Annotation a : getAnnotations(method)) {
            if (type.isInstance(a)) {
                ret.add(type.cast(a));
            }
        }
        return ret;
    }
}

Related

  1. getAnnotations(Enum targetEnum, Class targetAnnotationClass)
  2. getAnnotations(Field field)
  3. getAnnotations(final Class c, final Class annClass)
  4. getAnnotations(final Class clazz, final Class annotation)
  5. getAnnotations(final Class clazz, final String fieldName)
  6. getAnnotations(Method method)
  7. getAnnotations(Method method)
  8. getAnnotations(Method method)
  9. getAnnotations(Object instance)