#!/usr/bin/env groovy
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationWithClosure {
Class closure() default { true }
}
trait TraitWithAnnotatedField {
@AnnotationWithClosure(closure = {})
String foo
@AnnotationWithClosure()
String bar
}
class Main implements TraitWithAnnotatedField {
def printFields() {
this.class.declaredFields.each {
println "${it} is annotated ${it.isAnnotationPresent(AnnotationWithClosure.class)}"
}
}
}
new Main().printFields()
当我执行此脚本时,在控制台中我看到以下内容:
私有 java.lang.String Main.TraitWithAnnotatedField__bar 已注释:true
私有 java.lang.String Main.TraitWithAnnotatedField__foo 已注释:false
有人可以解释这种行为吗?如何正确地从 trait 字段中获取带有闭包的注释并在 groovy 中处理它们?
$ groovy -version
Groovy Version: 2.4.12 JVM: 1.8.0_144 Vendor: Azul Systems, Inc. OS: Linux