Description

get Annotation

License

Open Source License

Declaration

public static <A extends Annotation> A getAnnotation(Class<A> ac, AnnotatedElement m,
            Annotation... directAnnotations) 

Method Source Code


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

public class Main {
    public static <A extends Annotation> A getAnnotation(Class<A> ac, AnnotatedElement m,
            Annotation... directAnnotations) {
        return getAnnotation(ac, false, m, directAnnotations);
    }//  w w w  .  j  ava 2 s . c  o  m

    private static <A extends Annotation> A getAnnotation(Class<A> ac, boolean inherit, AnnotatedElement m,
            Annotation... directAnnotations) {
        if (directAnnotations != null) {
            for (Annotation ann : directAnnotations) {
                if (ac.isInstance(ann)) {
                    return ac.cast(ann);
                }
            }
        }

        if (m == null) {
            return null;
        }
        A a = m.getAnnotation(ac);
        if (a != null) {
            return a;
        }

        if (inherit) {
            if (m instanceof Member) {
                return getAnnotation(ac, inherit, ((Member) m).getDeclaringClass());
            }

            if (m instanceof Class<?>) {
                Class<?> c = (Class<?>) m, dc = c.getDeclaringClass();
                Class p = c.getSuperclass();
                while (p != null) {
                    a = getAnnotation(ac, true, p);
                    if (a != null) {
                        return a;
                    }
                    p = p.getSuperclass();
                }

                if (dc != null) {
                    return getAnnotation(ac, inherit, dc);
                }
            }
        }
        return null;
    }
}

Related

  1. getAnnotation(Class theClass, Class theAnnotation)
  2. getAnnotation(Class type, Class annotationType)
  3. getAnnotation(Class type, Class ann)
  4. getAnnotation(Class type, Class annotationType)
  5. getAnnotation(Class type, Class annotationClass)
  6. getAnnotation(Class annotationType, Class classType)
  7. getAnnotation(Class at, Enum enu)
  8. getAnnotation(Class realClass, String pAttributeName, Class annotationClass)
  9. getAnnotation(Class a, Class c)