Search code examples
xtend

Get Annotation parameter from ActiveAnnotation


I'm trying to implement a parameterized ActiveAnnotation and try to get the supplied annotations.

@Active(ExampleProcessor)
annotation ExampleAnnotation {
    val String value
}

class ExampleProcessor extends AbstractClassProcessor {
    override doRegisterGlobals(ClassDeclaration annotatedClass, extension RegisterGlobalsContext context)
    {
        val annotation = ??
        annotation.value
    }
}

What I did

annotatedClass.annotations.filter(ExampleAnnotation).head.value

which sadly leads to a null pointer when using it like so:

@ExampleAnnotation("Hello!")
class MyClass { }

Solution

  • annotatedClass.annotations consist of elements of AnnotationReference type, not Class<?>, you should look up a type for your class and then use it to filter out annotations, e.g.:

    val annotation = annotatedClass.findAnnotation(ExampleAnnotation.findUpstreamType)
    val value = annotation.getStringValue('value');