get annotations By Types - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Type

Description

get annotations By Types

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;
import java.util.*;

public class Main {
    public static Map<Class<?>, List<Annotation>> annotationsByTypes(
            Annotation... annotations) {
        Map<Class<?>, List<Annotation>> annotationMap = new HashMap<Class<?>, List<Annotation>>();
        for (Annotation annotation : annotations) {
            List<Annotation> annotationList = annotationMap.get(annotation
                    .getClass());/*from   w  ww  . ja  v  a 2  s  . com*/
            if (annotationList == null) {
                annotationList = new ArrayList<>();
            }
            annotationList.add(annotation);
            annotationMap.put(extractClass(annotation.getClass()),
                    annotationList);
        }
        return annotationMap;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> get(
            Map<Class<?>, List<Annotation>> annotationMap, Class<T> type) {
        if (annotationMap.containsKey(type)) {
            return (List<T>) annotationMap.get(type);
        } else {
            return Collections.emptyList();
        }
    }

    private static Class<?> extractClass(
            Class<? extends Annotation> annotationClass) {
        return annotationClass.getInterfaces()[0];
    }
}

Related Tutorials