Java Reflection Method Annotation getMethodAnnotation(Class a, Method m)

Here you can find the source of getMethodAnnotation(Class a, Method m)

Description

Returns the specified annotation on the specified method.

License

Apache License

Parameter

Parameter Description
a The annotation to search for.
m The method to search.

Return

The annotation, or null if it wasn't found.

Declaration

public static <T extends Annotation> T getMethodAnnotation(Class<T> a, Method m) 

Method Source Code

//package com.java2s;
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;

public class Main {
    /**//  w  ww .  j a va  2s.c  o m
     * Returns the specified annotation on the specified method.
     * <p>
     * Similar to {@link Method#getAnnotation(Class)}, but searches up the parent hierarchy for the annotation
     * defined on parent classes and interfaces.
     * <p>
     * Normally, annotations defined on methods of parent classes and interfaces are not inherited by the child
     * methods.
     * This utility method gets around that limitation by searching the class hierarchy for the "same" method.
     *
     * @param a The annotation to search for.
     * @param m The method to search.
     * @return The annotation, or <jk>null</jk> if it wasn't found.
     */
    public static <T extends Annotation> T getMethodAnnotation(Class<T> a, Method m) {
        T t = m.getAnnotation(a);
        if (t != null)
            return t;
        Class<?> pc = m.getDeclaringClass().getSuperclass();
        if (pc != null) {
            for (Method m2 : pc.getDeclaredMethods()) {
                if (isSameMethod(m, m2)) {
                    t = getMethodAnnotation(a, m2);
                    if (t != null)
                        return t;
                }
            }
        }
        for (Class<?> ic : m.getDeclaringClass().getInterfaces()) {
            for (Method m2 : ic.getDeclaredMethods()) {
                if (isSameMethod(m, m2)) {
                    t = getMethodAnnotation(a, m2);
                    if (t != null)
                        return t;
                }
            }
        }
        return null;
    }

    private static boolean isSameMethod(Method m1, Method m2) {
        return m1.getName().equals(m2.getName()) && Arrays.equals(m1.getParameterTypes(), m2.getParameterTypes());
    }
}

Related

  1. getMethod(Class annotationClass, Class aClass)
  2. getMethod(Class compClassOrSuper, Class annotation)
  3. getMethodAnnotatedWith(Class toIntrospect, Class c)
  4. getMethodAnnotation(final Method method, final Class annoClass)
  5. getMethodAnnotation(final Method method, final Class annotationType)
  6. getMethodAnnotation(Method method, Class annotation)
  7. getMethodAnnotation(Method method, Class annotationType)