从 AnnotationReference 中检索 Annotation 并创建调度方法

Retrieve Annotation from AnnotationReference and create dispatch methods

是否可以通过注解创建分派方法。我正在尝试创建以下场景:

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'''
}

定义的注解:

annotation Boolean {

}

annotation Password {

}

如何通过 AnnotationDeclaration class 访问注释?

AnnotationReference 表示注释的实例。它提供了一个 API 来访问实例的值和类型:

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 (…) {
    …
}