Here you can find the source of getAnnotation(Method method, Class
Parameter | Description |
---|---|
T | the type |
method | the method |
type | the type of annotation |
public static <T extends Annotation> T getAnnotation(Method method, Class<T> type)
//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.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<>(); /**//from ww w .j a v a2s.co m * Returns the first {@link Annotation} of the given type * defined on the given {@link Method}. * @param <T> the type * @param method the method * @param type the type of annotation * @return the annotation or null */ public static <T extends Annotation> T getAnnotation(Method method, Class<T> type) { for (Annotation a : getAnnotations(method)) { if (type.isInstance(a)) { return type.cast(a); } } return null; } /** * 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) { return filterAnnotations(getAnnotations(method), type); } /** * Returns all of the {@link Annotation}s defined on * the given {@link Method}. * @param method the {@link Method} * @return the {@link Annotation}s */ private static List<Annotation> getAnnotations(Method method) { if (methodAnnotationCache.containsKey(method)) { return methodAnnotationCache.get(method); } List<Annotation> annotations = new ArrayList<>(); Collections.addAll(annotations, method.getAnnotations()); annotations = Collections.unmodifiableList(annotations); methodAnnotationCache.put(method, annotations); return annotations; } private 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; } }