Java Reflection Annotation getAnnotation(Class clazz, Class ann)

Here you can find the source of getAnnotation(Class clazz, Class ann)

Description

Inspects the class passed in for the class level annotation specified.

License

Apache License

Parameter

Parameter Description
clazz class to inspect
ann annotation to search for. Must be a class-level annotation.

Return

the annotation instance, or null

Declaration

@SuppressWarnings("unchecked")
public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> ann) 

Method Source Code


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

import java.lang.annotation.Annotation;

public class Main {
    /**/*from w  w w  . j  a v a  2  s .  c o m*/
     * Inspects the class passed in for the class level annotation specified.  If the annotation is not available, this
     * method recursively inspects superclasses and interfaces until it finds the required annotation.
     * <p/>
     * Returns null if the annotation cannot be found.
     *
     * @param clazz class to inspect
     * @param ann   annotation to search for.  Must be a class-level annotation.
     * @return the annotation instance, or null
     */
    @SuppressWarnings("unchecked")
    public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> ann) {
        while (true) {
            // first check class
            T a = clazz.getAnnotation(ann);
            if (a != null)
                return a;

            // check interfaces
            if (!clazz.isInterface()) {
                Class<?>[] interfaces = clazz.getInterfaces();
                for (Class<?> inter : interfaces) {
                    a = getAnnotation(inter, ann);
                    if (a != null)
                        return a;
                }
            }

            // check superclasses
            Class<?> superclass = clazz.getSuperclass();
            if (superclass == null)
                return null; // no where else to look
            clazz = superclass;
        }
    }
}

Related

  1. getAnnotation(Class classForAnnotation, Class annotationClass)
  2. getAnnotation(Class clazz, Class annotationClass)
  3. getAnnotation(Class clazz, Class annotationClass)
  4. getAnnotation(Class clazz, Class annotClass, boolean forceInherit)
  5. getAnnotation(Class clazz, Class annotationClass)
  6. getAnnotation(Class clazz, Class annClazz)
  7. getAnnotation(Class clazz, Class annotation)
  8. getAnnotation(Class clazz, Class annotation)
  9. getAnnotation(Class clazz, Class annotationClass)