简体   繁体   中英

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.

Groovyc: Expected 'a' to be an inline constant of type char not a field expression in @MyAnnotation

I know that char in groovy is specified as

'a' as char

My Java custom annotation

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

    char someChar() default '#';

}

Not working Groovy code

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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