Java Reflection Annotation getAnnotation(Class a, Class c)

Here you can find the source of getAnnotation(Class a, Class c)

Description

Similar to Class#getAnnotation(Class) except also searches annotations on interfaces.

License

Apache License

Parameter

Parameter Description
T The annotation class type.
a The annotation class.
c The annotated class.

Return

The annotation, or null if not found.

Declaration

public static <T extends Annotation> T getAnnotation(Class<T> a, Class<?> c) 

Method Source Code

//package com.java2s;
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *

import java.lang.annotation.*;

public class Main {
    /**/*from  ww w.j  a va  2s .com*/
     * Similar to {@link Class#getAnnotation(Class)} except also searches annotations on interfaces.
     *
     * @param <T> The annotation class type.
     * @param a The annotation class.
     * @param c The annotated class.
     * @return The annotation, or <jk>null</jk> if not found.
     */
    public static <T extends Annotation> T getAnnotation(Class<T> a, Class<?> c) {
        if (c == null)
            return null;

        T t = getDeclaredAnnotation(a, c);
        if (t != null)
            return t;

        t = getAnnotation(a, c.getSuperclass());
        if (t != null)
            return t;

        for (Class<?> c2 : c.getInterfaces()) {
            t = getAnnotation(a, c2);
            if (t != null)
                return t;
        }
        return null;
    }

    /**
     * Returns the specified annotation only if it's been declared on the specified class.
     * <p>
     * More efficient than calling {@link Class#getAnnotation(Class)} since it doesn't
     *    recursively look for the class up the parent chain.
     *
     * @param <T> The annotation class type.
     * @param a The annotation class.
     * @param c The annotated class.
     * @return The annotation, or <jk>null</jk> if not found.
     */
    @SuppressWarnings("unchecked")
    public static <T extends Annotation> T getDeclaredAnnotation(Class<T> a, Class<?> c) {
        for (Annotation a2 : c.getDeclaredAnnotations())
            if (a2.annotationType() == a)
                return (T) a2;
        return null;
    }
}

Related

  1. getAnnotation(Class type, Class annotationClass)
  2. getAnnotation(Class ac, AnnotatedElement m, Annotation... directAnnotations)
  3. getAnnotation(Class annotationType, Class classType)
  4. getAnnotation(Class at, Enum enu)
  5. getAnnotation(Class realClass, String pAttributeName, Class annotationClass)
  6. getAnnotation(Class annotation, Class ownerClass, Method method)
  7. getAnnotation(Class annotationClass, Class cls)
  8. getAnnotation(Class annotationType, AnnotatedElement... objects)
  9. getAnnotation(Class cl, Object o)