是否可以在Annotations上创建调度方法。我正在尝试创建以下场景:
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类访问注释?
答案 0 :(得分:1)
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 (…) {
…
}