[英]Groovy - Unable to use static final string in an annotation
Something is really wierd.有些东西真的很奇怪。 I'm using a static final String in an annotation value.
我在注释值中使用静态最终字符串。
class Constants {
static final String myConstant = "ting tong"
}
class Service {
@CacheEvict(cacheNames = Constants.myConstant)
void doSomethingNice() {
}
}
However, i just cant get it to compile.但是,我无法编译它。
Here's the error message这是错误信息
Attribute 'myConstant' should have type 'java.lang.String';
属性“myConstant”的类型应该是“java.lang.String”; but found type 'java.lang.Object' in @org.springframework.cache.annotation.CacheEvict
但在@org.springframework.cache.annotation.CacheEvict 中发现类型'java.lang.Object'
Expected 'Constants.getMyConstant()' to be an inline constant of type java.lang.String in @org.springframework.cache.annotation.CacheEvict
预期 'Constants.getMyConstant()' 是 @org.springframework.cache.annotation.CacheEvict 中 java.lang.String 类型的内联常量
What can be the problem?可能是什么问题? This works perfectly in Java
这在 Java 中完美运行
In general it is a good practice to keep the constants under an Interface and not under class.一般来说,将常量保存在接口下而不是类下是一个很好的做法。
interface Constants {
public static final String myConstant = "ting tong"
}
Another good practice is to define constants as static final not just final, because it is more efficient to create only 1 instance for each constant.另一个好的做法是将常量定义为static final而不仅仅是 final,因为为每个常量只创建 1 个实例会更有效。
Turns out that the problem was due to the automatic getter/setter generation of Groovy.结果证明问题是由于 Groovy 的自动 getter/setter 生成造成的。 It would generate a getter for my constant and use it within the annotation, and i guess thats not allowed.
它会为我的常量生成一个 getter 并在注释中使用它,我想这是不允许的。
To fix, mark the field as public.要修复,请将字段标记为公开。 That would disable the automatic getter generation.
这将禁用自动吸气剂生成。
class Constants {
public static final String myConstant = "ting tong"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.