Returns information whether the given annotated element is annotated by some annotation which is marked by given (marker) annotation. - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Element

Description

Returns information whether the given annotated element is annotated by some annotation which is marked by given (marker) annotation.

Demo Code


import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main{
    /**//w ww . j  a  v a 2s.co  m
     * Returns information whether the given annotated element is annotated by some annotation which
     * is marked by given (marker) annotation.
     *
     * @param element the annotated element.
     * @param annotatedBy the annotation type which annotates searched annotations.
     * @return <code>true</code> if given element is annotated by annotation which is marked by given
     *         (marker) annotation; <code>false</code> otherwise.
     */
    public static boolean isAnnotatedAnnotationPresent(
            AnnotatedElement element,
            Class<? extends Annotation> annotatedBy) {
        Preconditions.checkArgumentNotNull(element,
                "Annotated element cannot be null");
        Preconditions.checkArgumentNotNull(annotatedBy,
                "Annotation cannot be null");

        Annotation[] annotations = element.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            Annotation[] annotationAnnotations = annotations[i]
                    .annotationType().getAnnotations();
            for (int j = 0; j < annotationAnnotations.length; j++) {
                Class<? extends Annotation> aType = annotationAnnotations[j]
                        .annotationType();
                if (annotatedBy.equals(aType)) {
                    return true;
                }
            }
        }

        return false;
    }
}

Related Tutorials