Java Reflection Annotation getAnnotation(Class theClass, Class theAnnotation)

Here you can find the source of getAnnotation(Class theClass, Class theAnnotation)

Description

Return the given annotation from the class.

License

Apache License

Parameter

Parameter Description
theClass the class to inspect
theAnnotation the annotation to retrieve

Return

the class's annotation, or it's "inherited" annotation, or null if the annotation cannot be found.

Declaration

public static <T extends Annotation> T getAnnotation(Class<?> theClass, Class<T> theAnnotation) 

Method Source Code


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

import java.lang.annotation.Annotation;

public class Main {
    /**// w  w w . j  av a 2  s . co m
     * Return the given annotation from the class.  If the class does not have the annotation, it's parent class and any
     * interfaces will also be checked.
     * @param theClass the class to inspect
     * @param theAnnotation the annotation to retrieve
     * @return the class's annotation, or it's "inherited" annotation, or null if the annotation cannot be found.
     */
    public static <T extends Annotation> T getAnnotation(Class<?> theClass, Class<T> theAnnotation) {
        T aAnnotation = null;

        if (theClass.isAnnotationPresent(theAnnotation)) {
            aAnnotation = theClass.getAnnotation(theAnnotation);
        } else {
            if (shouldInspectClass(theClass.getSuperclass()))
                aAnnotation = getAnnotation(theClass.getSuperclass(), theAnnotation);

            if (aAnnotation == null) {
                for (Class<?> aInt : theClass.getInterfaces()) {
                    aAnnotation = getAnnotation(aInt, theAnnotation);
                    if (aAnnotation != null) {
                        break;
                    }
                }
            }
        }
        return aAnnotation;
    }

    private static boolean shouldInspectClass(final Class<?> theClass) {
        return !Object.class.equals(theClass) && theClass != null;
    }
}

Related

  1. getAnnotation(Class klazz, Class annotationClass)
  2. getAnnotation(Class objectClass, Class annotationClass)
  3. getAnnotation(Class onClass, Class desiredAnnotationClass)
  4. getAnnotation(Class target, Class annoCls)
  5. getAnnotation(Class target, Class annotationClass)
  6. getAnnotation(Class type, Class annotationType)
  7. getAnnotation(Class type, Class ann)
  8. getAnnotation(Class type, Class annotationType)
  9. getAnnotation(Class type, Class annotationClass)