简体   繁体   English

注释元数据的 Groovy 字符文字?

[英]Groovy character literal for annotation metadata?

I wanted to test my Java custom annotation in Groovy but did not manage it because of the char issue.我想在 Groovy 中测试我的Java自定义注释,但由于字符问题而没有管理它。

Groovyc: Expected 'a' to be an inline constant of type char not a field expression in @MyAnnotation Groovyc:预期“a”是 char 类型的内联常量,而不是 @MyAnnotation 中的字段表达式

I know that char in groovy is specified as我知道 groovy 中的char被指定为

'a' as char

My Java custom annotation我的Java自定义注解

@Target({FIELD})
@Retention(RUNTIME)
@Documented
public @interface MyAnnotation {

    char someChar() default '#';

}

Not working Groovy code不工作的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

}

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 .其中importart部分是as char的注解定义(除非这是Java的不Groovy中),该char在注解的使用投,而不是as char而是使该类沿着硬铸铁@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.这似乎对我有用,但是如果您可以访问注释代码,您也可以将其更改为字符串,因为我认为使用字符串更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM