Java Reflection Annotation getAnnotation(Annotation[] annotations, Class annotationType)

Here you can find the source of getAnnotation(Annotation[] annotations, Class annotationType)

Description

Gets the annotation that has the specified type, or null if there isn't one

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
public static <A extends Annotation> A getAnnotation(Annotation[] annotations, Class<A> annotationType) 

Method Source Code


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

import java.lang.annotation.Annotation;

import java.util.HashMap;
import java.util.Map;

public class Main {
    /** A map of the primitive types to their wrapper types */
    private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = new HashMap<>();

    /** Gets the annotation that has the specified type, or null if there isn't one */
    @SuppressWarnings("unchecked")
    public static <A extends Annotation> A getAnnotation(Annotation[] annotations, Class<A> annotationType) {
        for (Annotation anno : annotations)
            if (annotationType.isAssignableFrom(anno.getClass()))
                return (A) anno;

        return null;
    }/* w  ww .  j  a  v  a  2 s . c  o  m*/

    /**
     * Just like Class.isAssignableFrom(), but does the right thing when considering autoboxing.
     */
    public static boolean isAssignableFrom(Class<?> to, Class<?> from) {
        Class<?> notPrimitiveTo = to.isPrimitive() ? PRIMITIVE_TO_WRAPPER.get(to) : to;
        Class<?> notPrimitiveFrom = from.isPrimitive() ? PRIMITIVE_TO_WRAPPER.get(from) : from;

        return notPrimitiveTo.isAssignableFrom(notPrimitiveFrom);
    }
}

Related

  1. getAnnotation(AnnotatedElement element, Class annotation)
  2. getAnnotation(AnnotatedElement element, String annotationTypeName)
  3. getAnnotation(AnnotatedElement target, String annotationType)
  4. getAnnotation(Annotation ann, Class annotationType)
  5. getAnnotation(Annotation[] annotaions, Class T)
  6. getAnnotation(Annotation[] annotations, Class annotationClazz)
  7. getAnnotation(Annotation[] annotations, Class annotationType)
  8. getAnnotation(Annotation[] annotations, Class clazz)
  9. getAnnotation(Class clazz, Class annotation)