Java Reflection Annotation getAnnotation(final Method method, final Class annotationClass)

Here you can find the source of getAnnotation(final Method method, final Class annotationClass)

Description

get Annotation

License

Open Source License

Declaration

public static <T extends Annotation> T getAnnotation(final Method method, final Class<T> annotationClass) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012, 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //from  www. j a  v  a2  s . c  o  m
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

public class Main {
    public static <T extends Annotation> T getAnnotation(final Method method, final Class<T> annotationClass) {
        T annotation = method.getAnnotation(annotationClass);
        if (annotation != null)
            return annotation;

        final Class<?> declaringClass = method.getDeclaringClass();
        Class<?> superClass = declaringClass.getSuperclass();

        while (superClass != null) {
            try {
                final Method superClassMethod = superClass.getDeclaredMethod(method.getName(),
                        method.getParameterTypes());
                return getAnnotation(superClassMethod, annotationClass);
            } catch (final Exception exception) {
                // Ignore and exit here
                return null;
            }
        }
        return null;
    }
}

Related

  1. getAnnotation(final Class annotatedClass, final Class annotationClass)
  2. getAnnotation(final Class type, final Class annotation)
  3. getAnnotation(final Class reference, final AccessibleObject obj)
  4. getAnnotation(final Class annotationClass, final AnnotatedElement... elements)
  5. getAnnotation(final Member member, final Class annotation)
  6. getAnnotation(final Object obj, final Class annoType)
  7. getAnnotation(final Object object, final Class annotationClass)
  8. getAnnotation(Member m, Class annotationClass)
  9. getAnnotation(Method m, Class annotationClass)