Checks if a Class or Method are annotated with the given annotation - Java Reflection

Java examples for Reflection:Method

Description

Checks if a Class or Method are annotated with the given annotation

Demo Code


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

public class Main {
    /**/* w ww.j  av  a2 s . co  m*/
     * Checks if a Class or Method are annotated with the given annotation
     *
     * @param elem                 the Class or Method to reflect on
     * @param annotationType       the annotation type
     * @param checkMetaAnnotations check for meta annotations
     * @return true if annotations is present
     */
    public static boolean hasAnnotation(AnnotatedElement elem,
            Class<? extends Annotation> annotationType,
            boolean checkMetaAnnotations) {
        if (elem.isAnnotationPresent(annotationType)) {
            return true;
        }
        if (checkMetaAnnotations) {
            for (Annotation a : elem.getAnnotations()) {
                for (Annotation meta : a.annotationType().getAnnotations()) {
                    if (meta.annotationType().getName()
                            .equals(annotationType.getName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

Related Tutorials