get Annotations from AnnotatedElement - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Element

Description

get Annotations from AnnotatedElement

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.Collection;

public class Main {
    public static <T extends Annotation> Collection<T> getAnnotations(
            AnnotatedElement ae, Class<T> annotationType) {
        Collection<T> anns = new ArrayList<>(2);

        // look at raw annotation
        T ann = ae.getAnnotation(annotationType);
        if (ann != null) {
            anns.add(ann);//from   ww w .  j av a 2  s  .co  m
        }

        // scan meta-annotations
        for (Annotation metaAnn : ae.getAnnotations()) {
            ann = metaAnn.annotationType().getAnnotation(annotationType);
            if (ann != null) {
                anns.add(ann);
            }
        }

        return (anns.isEmpty() ? null : anns);
    }
}

Related Tutorials