Java Reflection Annotation Find findAnnotation(Class clazz, Class annotationType)

Here you can find the source of findAnnotation(Class clazz, Class annotationType)

Description

find Annotation

License

Open Source License

Declaration

public static <T extends Annotation> T findAnnotation(Class clazz, Class<T> annotationType) 

Method Source Code


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

public class Main {
    public static <T extends Annotation> T findAnnotation(Method method, Class<T> annotationType) {
        T annotation = getAnnotation(method, annotationType);
        Class cl = method.getDeclaringClass();
        do {// w  ww .  j a va2s.c o  m
            if (annotation != null)
                break;
            cl = cl.getSuperclass();
            if (cl == null || cl.equals(Object.class))
                break;
            try {
                Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
                annotation = getAnnotation(equivalentMethod, annotationType);
            } catch (NoSuchMethodException ex) {
            }
        } while (true);
        return annotation;
    }

    public static <T extends Annotation> T findAnnotation(Class clazz, Class<T> annotationType) {
        T annotation = (T) clazz.getAnnotation(annotationType);
        if (annotation != null)
            return annotation;
        Class clazzes[] = clazz.getInterfaces();
        int len = clazzes.length;
        for (int i = 0; i < len; i++) {
            Class ifc = clazzes[i];
            annotation = findAnnotation(ifc, annotationType);
            if (annotation != null)
                return annotation;
        }
        if (clazz.getSuperclass() == null || Object.class.equals(clazz.getSuperclass()))
            return null;
        else
            return findAnnotation(clazz.getSuperclass(), annotationType);
    }

    public static <T extends Annotation> T getAnnotation(Field field, Class<T> annotationType) {
        return field.getAnnotation(annotationType);
    }

    public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationType) {
        return method.getAnnotation(annotationType);
    }
}

Related

  1. findAnnotation(AnnotatedElement element, Class annotationType)
  2. findAnnotation(Annotation parentAnnotation, Class annotationType)
  3. findAnnotation(Annotation[] parameterAnnotations, Class targetAnnotation)
  4. findAnnotation(Annotation[] searchList, Class annotation)
  5. findAnnotation(Class clazz, Class annotationType)
  6. findAnnotation(Class aClass, Class annotationClass)
  7. findAnnotation(Class classy, Class targetAnnotation)
  8. findAnnotation(Class clazz, Class annotationClass, Set> set)
  9. findAnnotation(Class clazz, Class annotationClass)