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()

When I execute this script, in console I see following:

private java.lang.String Main.TraitWithAnnotatedField__bar is annotated : true
private java.lang.String Main.TraitWithAnnotatedField__foo is annotated : false

Can someone explain this behavior? How to correctly get annotations with closures from trait fields and process them in groovy?

$ groovy -version
Groovy Version: 2.4.12 JVM: 1.8.0_144 Vendor: Azul Systems, Inc. OS: Linux

1 Answers1

1

This is the default behaviour of Groovy, sadly.

Annotating your trait with @CompileStatic solves the problem though.

renke
  • 1,180
  • 2
  • 12
  • 27