Returns true if the given type has a method with the given annotation - Java Reflection

Java examples for Reflection:Method

Description

Returns true if the given type has a method with the given annotation

Demo Code


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

import java.lang.reflect.Method;

public class Main {
    /**/*from w  w w  .  j a  v a 2 s  .com*/
     * Returns true if the given type has a method with the given annotation
     */
    public static boolean hasMethodWithAnnotation(Class<?> type,
            Class<? extends Annotation> annotationType,
            boolean checkMetaAnnotations) {
        try {
            do {
                Method[] methods = type.getDeclaredMethods();
                for (Method method : methods) {
                    if (hasAnnotation(method, annotationType,
                            checkMetaAnnotations)) {
                        return true;
                    }
                }
                type = type.getSuperclass();
            } while (type != null);
        } catch (Throwable e) {
            // ignore a class loading issue
        }
        return false;
    }

    /**
     * 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