实现带有注释字段的 trait 的类,如果注释包含闭包字段,则会丢失 trait 字段上的注释。

3
#!/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()

当我执行这个脚本时,控制台显示如下内容:

private java.lang.String Main.TraitWithAnnotatedField__bar已经被注释:true
private 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
1个回答

1
这是Groovy的默认行为,遗憾的是。
在你的trait上注释@CompileStatic可以解决这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接