【发布时间】:2014-01-22 14:49:53
【问题描述】:
在 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
}
}
在这里,方法myMethod 用@MyGroovyAnnotation 注释,如果我传递一个像@MyGroovyAnnotation(value="Something") 这样的字符串文字,它可以完美地工作,但是如果我尝试像上面的例子一样传递VALUE,我得到:
来自 Eclipse:
Groovy:Expected 'VALUE' to be an inline constant of type java.lang.String in @MyGroovyAnnotation
从 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
有没有人知道我需要做什么才能让它工作,或者是否有可能?感谢您提供的任何帮助或见解。
【问题讨论】:
-
谢谢@tim_yates,我没发现那个。那里的问题类似,但选择的答案并不是真正的解决方案,因为它没有任何区别。我会赞成引用 groovy bug 链接的答案,但我还没有足够的声誉来做到这一点。我将检查这个错误,看看我是否可以为这个问题和那个旧问题提供更多信息。再次感谢!
标签: groovy annotations