Estoy tratando de leer el valor de una enumeración en una anotación usando un procesador de anotación y un espejo de anotación, pero me estoy volviendo nulo. Creo que esto tiene que ver con AnnotationValue envolviendo un Enum como un elemento variable. El documento para VariableElement # getConstantValue() dice "Devuelve el valor de esta variable si se trata de un campo final inicializado a una constante en tiempo de compilación". Está bien, pero el final no es un modificador válido para un miembro de anotación. También es de destacar que no tengo problemas para leer otros valores de anotación, solo Enumeraciones.Cómo capturar un Enum de un AnnotationValue en un procesador de anotaciones
He investigado un poco y parece que AnnotationValue está instanciado como Symbol.VarSymbol en tiempo de ejecución, pero Symbol.VarSymbol # getConstantValue() parece que debería devolver el objeto.
Finalmente, si hago un toString() en AnnotationValue obtengo el valor correcto.
la anotación:
package annotation;
public @interface AnAnnotation
{
String value();
Behavior defaultBehavior() default Behavior.NEW;
public static enum Behavior
{
NEW, NULL;
}
}
Parte de mi procesador y anidado dentro de un gran número de bucles para llegar a la AnnotaionMirror adecuada:
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues = elemUtils.getElementValuesWithDefaults(annotationMirror);
for (ExecutableElement method : annotationValues.keySet())
{
...
else if ("defaultBehavior".equals(method.getSimpleName().toString()))
{
defaultBehavior = (Behavior)((VariableElement)annotationValues.get(method).getValue()).getConstantValue();
// This prints "NEW" or "NULL" correctly
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,annotationValues.get(method).toString());
// This prints null incorrectly (expect "NEW" or "NULL")
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, defaultBehavior + "");
}
...
}
EDIT: una versión más completa del procesador.
package annotation.processor;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import javax.tools.*;
import annotation.AnAnnotation;
import annotation.AnAnnotation.Behavior;
@SupportedAnnotationTypes("annotation.AnAnnotation")
public class AnAnnotationProcessor extends AbstractProcessor
{
Types typeUtils;
Elements elemUtils;
@Override
public void init(ProcessingEnvironment processingEnv)
{
super.init(processingEnv);
typeUtils = processingEnv.getTypeUtils();
elemUtils = processingEnv.getElementUtils();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv)
{
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
"Entering AnnotationNullableClassProcessor");
/****** Iterate over all annotaions being processed (only AnAnnotation) ******/
for (TypeElement annotation : annotations)
{
/****** Iterate over all elements that are annotated with the annotation ******/
for (Element element : roundEnv.getElementsAnnotatedWith(annotation))
{
/****** Iterate over all the declared annotations of the element ******/
for (AnnotationMirror annotationMirror : element.getAnnotationMirrors())
{
final String annotationTypeName = annotationMirror.getAnnotationType().toString();
// Process annotations of type AnAnnotation
if (annotationTypeName.equals(AnAnnotation.class.getName()))
{
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues = elemUtils.getElementValuesWithDefaults(annotationMirror);
/****** Iterate over the annotation's values. ******/
for (ExecutableElement method : accessorValues.keySet())
{
if ("defaultBehavior".equals(method.getSimpleName().toString()))
{
Behavior defaultBehavior = (Behavior)((VariableElement)annotationValues.get(method).getValue()).getConstantValue();
// This prints "NEW" or "NULL" correctly
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,annotationValues.get(method).toString());
// This prints null incorrectly (expect "NEW" or "NULL")
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, defaultBehavior + "");
}
}
}
}
}
}
return true;
}
}
Olvidé mencionar que esta es la versión Java SE 6 del proceso de anotación. –