有没有办法将常量传递给Groovy中的注释? [英] Is there a way to pass a constant to an annotation in Groovy?
问题描述
例如:
@Retention(RetentionPolicy.RUNTIME)
@Target(value = [ElementType.METHOD])
public @interface MyGroovyAnnotation {
String value()
}
$ b $ class MyGroovyClass {
public static final String VALUE =Something
@MyGroovyAnnotation(value = VALUE)
public String myMethod(String value){
返回值
}
}
$ b在这里,
myMethod
方法用@注释MyGroovyAnnotation
,如果我传递像@MyGroovyAnnotation(value =Something)
的字符串文字,它可以很好地工作,但如果我试图传递VALUE
在上面的例子中,我得到:
从Eclipse开始:
<$ p $ Groovy:预计'VALUE'是@MyGroovyAnnotation中的java.lang.String类型的内联常量
从GroovyConsole运行:
expect'VALUE'是一个类型为java.lang的内联常量.String不是@MyGroovyAnnotation中的字段表达式
在行:20,列:31
属性'value'应该具有类型'java.lang.String';但在@MyGroovyAnnotation
中找到类型为'java.lang.Object'的行:-1,列:-1
有没有人知道我需要做些什么才能使其发挥作用,或者甚至有可能?感谢您提供任何帮助或见解。
我遇到了同样的问题,杰拉德的答案很奏效,例如:
<$ p $
@Target(value = [ElementType.METHOD])
public @interface MyGroovyAnnotation {
字符串值()$ b $ {code> @Retention(RetentionPolicy.RUNTIME) b
$ b $ class MyGroovyClass {
public static final String VALUE =Something
@MyGroovyAnnotation(value = MyGroovyClass.VALUE)
公共字符串myMethod(字符串值){
返回值
}
}
我想对接受的答案留言,但我没有50的声望。
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.
这篇关于有没有办法将常量传递给Groovy中的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!