Returns the annotation of the annotationClass of the clazz or any of it super classes. - Java java.lang.annotation

Java examples for java.lang.annotation:Class Annotation

Description

Returns the annotation of the annotationClass of the clazz or any of it super classes.

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;

public class Main {


    /**/*from   www .  j a  v  a2s .  co  m*/
     * Returns the annotation of the annotationClass of the clazz or any of it super classes.
     * 
     * @param clazz
     *           The class to inspect.
     * @param annotationClass
     *           Class of the annotation to return
     *           
     * @return The annotation of annnotationClass if found else null.
     */
    public static <T extends Annotation> T getAnnotation(Class<?> target,
            Class<T> annotationClass) {
        Class<?> clazz = target;
        T annotation = clazz.getAnnotation(annotationClass);
        if (annotation != null) {
            return annotation;
        }
        while ((clazz = clazz.getSuperclass()) != null) {
            annotation = clazz.getAnnotation(annotationClass);
            if (annotation != null) {
                return annotation;
            }
        }
        return null;
    }
}

Related Tutorials