Java Reflection Annotation getAnnotationMemberDefaults(Annotation annotation)

Here you can find the source of getAnnotationMemberDefaults(Annotation annotation)

Description

get Annotation Member Defaults

License

Apache License

Declaration

@SuppressWarnings("rawtypes")
    public static Map getAnnotationMemberDefaults(Annotation annotation) throws ReflectiveOperationException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;

public class Main {
    @SuppressWarnings("rawtypes")
    public static Map getAnnotationMemberDefaults(Annotation annotation) throws ReflectiveOperationException {
        Field[] fields = annotation.getClass().getSuperclass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);/*from  w  ww  .j a  v a  2s.  c  o  m*/
            Object instance = field.get(annotation);
            if (isAnnotationInvocationHandler(instance.getClass())) {
                Field typeField = instance.getClass().getDeclaredField("type");
                typeField.setAccessible(true);
                Object typeInstance = typeField.get(instance);

                Field annotationTypeField = typeInstance.getClass().getDeclaredField("annotationType");
                annotationTypeField.setAccessible(true);
                Object annotationTypeInstance = annotationTypeField.get(typeInstance);

                Field memberDefaultsField = annotationTypeInstance.getClass().getDeclaredField("memberDefaults");
                memberDefaultsField.setAccessible(true);
                Map memberDefaults = (Map) memberDefaultsField.get(annotationTypeInstance);

                return memberDefaults;
            }
        }

        return Collections.emptyMap();
    }

    private static boolean isAnnotationInvocationHandler(Class<?> clazz) {
        try {
            clazz.getDeclaredField("memberMethods");
            clazz.getDeclaredField("memberValues");
            clazz.getDeclaredField("type");
        } catch (NoSuchFieldException e) {
            return false;
        }

        return true;
    }
}

Related

  1. getAnnotationFullname(Annotation annotation)
  2. getAnnotationInClass( final Class annotationClass, final Class clazz)
  3. getAnnotationInHeirarchy(Class annotationClass, Class aClass)
  4. getAnnotationInherited(Class type, Class annotationClass)
  5. getAnnotationInstances(Class clazz, Class annotationClass)
  6. getAnnotationMemberType(Annotation annotation, String memberName)
  7. getAnnotationMetaAnnotated( AnnotatedElement annotatedElementClass, Class metaAnnotationToFind)
  8. getAnnotationMethods(Class annotationType)
  9. getAnnotationOfField(Field field, Class clazz)