Java Reflection Annotation getAnnotation(final Class type, final Class annotation)

Here you can find the source of getAnnotation(final Class type, final Class annotation)

Description

get Annotation

License

Open Source License

Parameter

Parameter Description
type type to examine
annotation annotation to search
T annotation type

Return

found annotation or null

Declaration

public static <T extends Annotation> T getAnnotation(final Class<?> type, final Class<T> annotation) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.annotation.Annotation;

import java.lang.reflect.Modifier;

public class Main {
    /**//from  w w w. ja  v a  2s .c  o  m
     * @param type       type to examine
     * @param annotation annotation to search
     * @param <T>        annotation type
     * @return found annotation or null
     */
    public static <T extends Annotation> T getAnnotation(final Class<?> type, final Class<T> annotation) {
        T res = null;
        if (!Modifier.isAbstract(type.getModifiers())) {
            Class<?> supertype = type;
            while (supertype != null && Object.class != supertype) {
                if (supertype.isAnnotationPresent(annotation)) {
                    res = supertype.getAnnotation(annotation);
                    break;
                }
                supertype = supertype.getSuperclass();
            }
        }
        return res;
    }
}

Related

  1. getAnnotation(Class lookingFor, Annotation[] annotations)
  2. getAnnotation(Enum enumConstant, Class annotationClass)
  3. getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass)
  4. getAnnotation(final Class c, final Class annClass)
  5. getAnnotation(final Class annotatedClass, final Class annotationClass)
  6. getAnnotation(final Class reference, final AccessibleObject obj)
  7. getAnnotation(final Class annotationClass, final AnnotatedElement... elements)
  8. getAnnotation(final Member member, final Class annotation)
  9. getAnnotation(final Method method, final Class annotationClass)