Java Reflection Annotation getAnnotationValue(Annotation annotation, String value, Class expectedType)

Here you can find the source of getAnnotationValue(Annotation annotation, String value, Class expectedType)

Description

Return a value from an annotation.

License

Open Source License

Parameter

Parameter Description
annotation The annotation.
value The value.
expectedType The expected type.
T The expected type.

Return

The value.

Declaration

private static <T> T getAnnotationValue(Annotation annotation, String value, Class<T> expectedType) 

Method Source Code


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

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Main {
    /**/*  ww w .j  a  v  a  2s  .c o m*/
     * Return a value from an annotation.
     * 
     * @param annotation
     *            The annotation.
     * @param value
     *            The value.
     * @param expectedType
     *            The expected type.
     * @param <T>
     *            The expected type.
     * @return The value.
     */
    private static <T> T getAnnotationValue(Annotation annotation, String value, Class<T> expectedType) {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        Method valueMethod;
        try {
            valueMethod = annotationType.getDeclaredMethod(value);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException(
                    "Cannot resolve required method '" + value + "()' for '" + annotationType + "'.");
        }
        Object elementValue;
        try {
            elementValue = valueMethod.invoke(annotation);
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException("Cannot invoke method value() for " + annotationType);
        }
        return elementValue != null ? expectedType.cast(elementValue) : null;
    }
}

Related

  1. getAnnotationsOf(Class annoClass)
  2. getAnnotationsRecursive(Class clazz)
  3. getAnnotationsRecursive(final Class type, final Class annotationType)
  4. getAnnotationValue(@Nonnull Class cls, @Nonnull Class annotation, V def)
  5. getAnnotationValue(Annotation annotation, String attributeName)
  6. getAnnotationValue(Annotation annotation, String valueName)
  7. getAnnotationValue(Class anno, Field field, String paramName)
  8. getAnnotationValue(final A annotation, final Function valueRetriever, final V defaultValue)
  9. getAnnotationValue(Object aObj, String aValue)