In Java, it's possible to pass a constant String as a parameter to an annotation, but I can't figure out how to do the same in Groovy.
For example:
@Retention(RetentionPolicy.RUNTIME)
@Target(value=[ElementType.METHOD])
public @interface MyGroovyAnnotation {
String value()
}
class MyGroovyClass {
public static final String VALUE = "Something"
@MyGroovyAnnotation(value=VALUE)
public String myMethod(String value) {
return value
}
}
Here, where the method myMethod
is annotated with @MyGroovyAnnotation
, if I pass a String literal like @MyGroovyAnnotation(value="Something")
, it works perfectly, but if I try to pass VALUE
like in the example above, I get:
From Eclipse:
Groovy:Expected 'VALUE' to be an inline constant of type java.lang.String in @MyGroovyAnnotation
Running from GroovyConsole:
expected 'VALUE' to be an inline constant of type java.lang.String not a field expression in @MyGroovyAnnotation
at line: 20, column: 31
Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' in @MyGroovyAnnotation
at line: -1, column: -1
Does anybody have any idea what I need to do to get this to work, or if it's even possible? Thanks for any help or insight you can provide.
I ran into this same issue and Gerard's answer works, but I didn't need to make a new Constants class, just refer to the existing class.
For example:
@Retention(RetentionPolicy.RUNTIME)
@Target(value=[ElementType.METHOD])
public @interface MyGroovyAnnotation {
String value()
}
class MyGroovyClass {
public static final String VALUE = "Something"
@MyGroovyAnnotation(value=MyGroovyClass.VALUE)
public String myMethod(String value) {
return value
}
}
I wanted to leave a comment on the accepted answer, but I didn't have 50 reputation.