注释元数据的 Groovy 字符文字? [英] Groovy character literal for annotation metadata?
问题描述
我想在 Groovy 中测试我的 Java 自定义注释,但由于字符问题而没有对其进行管理.
I wanted to test my Java custom annotation in Groovy but did not manage it because of the char issue.
Groovyc:预期 'a' 是 char 类型的内联常量,而不是 @MyAnnotation 中的字段表达式
Groovyc: Expected 'a' to be an inline constant of type char not a field expression in @MyAnnotation
我知道 groovy 中的 char 被指定为
I know that char in groovy is specified as
'a' as char
我的Java自定义注解
@Target({FIELD})
@Retention(RUNTIME)
@Documented
public @interface MyAnnotation {
char someChar() default '#';
}
不工作Groovy代码
class Foo {
@MyAnnotation(someChar = 'a' as char)
Object hoo
}
如果您将字符提取为常量,它也不起作用.
If you extract the char as a constant, it does not work either.
推荐答案
这是一个棘手的问题...我发现有效的是:
This is a tricky one... what I found to work was:
import java.lang.annotation.Documented
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
import groovy.transform.CompileStatic
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
char someChar() default ('#' as char);
}
@CompileStatic
class Foo {
@MyAnnotation(someChar =( (char)'a'))
Object hoo
}
其中importart部分是注解定义中的as char
(除非它是Java而不是Groovy),char
在注解用法中强制转换,而不是作为 char
,但在制作该类 @CompileStatic
的同时进行了强制转换.这似乎对我有用,但如果您可以访问注释代码,您也可以将其更改为字符串,因为我认为使用字符串更简单.
where the importart parts are the as char
in the annotation definition (unless that is Java not Groovy), the char
cast in the annotation usage, not as char
but a hard cast along with making that class @CompileStatic
. This seems to work for me, but if you have access to the annotation code you could also just change it to a String as I think I had it working simpler with a String.
这篇关于注释元数据的 Groovy 字符文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!