Java Reflection Annotation getAnnotation(Class clazz, Class annotationClass)

Here you can find the source of getAnnotation(Class clazz, Class annotationClass)

Description

get Annotation

License

Apache License

Declaration

public static <R extends Annotation> R getAnnotation(Class<?> clazz, Class<R> annotationClass) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.annotation.Annotation;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static <R extends Annotation> R getAnnotation(Class<?> clazz, Class<R> annotationClass) {
        return (R) findAnnotation(clazz, annotationClass, new HashSet<>());
    }/*  www  . j  av a 2  s  . co  m*/

    private static Annotation findAnnotation(Class<?> clazz, Class<? extends Annotation> annotationClass,
            Set<Class<?>> set) {
        if (clazz == null || set.contains(clazz) || clazz.equals(Object.class)) {
            return null;
        }

        set.add(clazz);

        Annotation result = findAnnotation(clazz.getSuperclass(), annotationClass, set);

        if (result != null) {
            return result;
        }

        Annotation findResult = Arrays.stream(clazz.getInterfaces())
                .map((Class<?> interf) -> findAnnotation(interf, annotationClass, set))
                .filter((Annotation annotation) -> annotation != null).findFirst().orElse(null);

        if (findResult != null) {
            return findResult;
        }

        Annotation interfaceAnnotation = Arrays.stream(clazz.getDeclaredAnnotations())
                .filter((Annotation annotation) -> annotation.annotationType().equals(annotationClass)).findFirst()
                .orElse(null);

        if (interfaceAnnotation != null) {
            return interfaceAnnotation;
        }

        return Arrays.stream(clazz.getDeclaredAnnotations())
                .map((Annotation annotation) -> findAnnotation(annotation.annotationType(), annotationClass, set))
                .filter((Annotation annotation) -> annotation != null).findFirst().orElse(null);
    }
}

Related

  1. getAnnotation(Class c, Class annotationClass)
  2. getAnnotation(Class classForAnnotation, Class annotationClass)
  3. getAnnotation(Class clazz, Class annotationClass)
  4. getAnnotation(Class clazz, Class annotationClass)
  5. getAnnotation(Class clazz, Class annotClass, boolean forceInherit)
  6. getAnnotation(Class clazz, Class ann)
  7. getAnnotation(Class clazz, Class annClazz)
  8. getAnnotation(Class clazz, Class annotation)
  9. getAnnotation(Class clazz, Class annotation)