在Java中,可以将常量String作为参数传递给注释,但我无法弄清楚如何在Groovy中执行相同的操作.
例如:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
这里,在方法myMethod注释的地方@MyGroovyAnnotation,如果我传递一个字符串文字@MyGroovyAnnotation(value="Something"),它可以很好地工作,但是如果我尝试VALUE在上面的例子中传递,我得到:
来自Eclipse:
Groovy:Expected 'VALUE' to be an inline constant of type java.lang.String in @MyGroovyAnnotation
Run Code Online (Sandbox Code Playgroud)
从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 …Run Code Online (Sandbox Code Playgroud)