Search code examples
annotationsjvmxtend

Retrieve Annotation from AnnotationReference and create dispatch methods


Is it possible to create dispatch methods over Annotations. I'm trying to create the following scenario:

def generateField(FieldDeclaration field, ClassDeclaration clazz) {
    '''
        «field.annotations.map[it.generateAnnotation(field)].join»
        '''
}

def dispatch generateAnnotation(Password annotation, FieldDeclaration field){
    '''//Password field'''
}

def dispatch generateAnnotation(Boolean annotation, FieldDeclaration field){
    '''//Boolean field'''
}

the defined annotations:

annotation Boolean {

}

annotation Password {

}

How can I access the annotation over the AnnotationDeclaration class?


Solution

  • AnnotationReference represents an instance of annotation. It provides an API to access values of an instance as well as a type:

    val passwordAnnotation = Password.findTypeGlobally
    val booleanAnnotation = Boolean.findTypeGlobally
    
    val AnnotationReference annotation = field.annotations.head
    // get a type
    val annotationType = annotation.annotationTypeDeclaration
    // check whether the type is Password
    if (passwordAnnotation.isAssignableFrom(annotationType)) {
        // get a value of 'myValue' field as integer
        val int value = annotation.getIntValue('myValue')
        …
    } else if (booleanAnnotation.isAssignableFrom(annotationType)) {
        …
    } else if (…) {
        …
    }