简体   繁体   中英

Groovy constant String as annotation value

Given the following classes (editor is the package name):

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Annot {
      String value();
}

public class JavaTest {
    public static final String TEST_STRING = "test";

    @Annot(TEST_STRING) //works
    private int a;
}

public class GroovyClass {
    public static final String TEST_STRING = 'test';
    public static final String TEST_STRING_MULTILINE = '''test''';
    public static final String TEST_GSTRING = "test";
    public static final String TEST_GSTRING_MULTILINE = """test""";

    @Annot(TEST_GSTRING) //Groovy:Expected 'TEST_GSTRING' to be an inline constant of type java.lang.String not a field expression in @editor.Annot
    private int a;

    @Annot(TEST_STRING_MULTILINE) //Groovy:Expected 'TEST_STRING_MULTILINE' to be an inline constant of type java.lang.String not a field expression in @editor.Annot
    private int b;

    @Annot(TEST_GSTRING) //Groovy:Expected 'TEST_GSTRING' to be an inline constant of type java.lang.String not a field expression in @editor.Annot
    private int c;

    @Annot(TEST_GSTRING_MULTILINE) //Groovy:Expected 'TEST_GSTRING_MULTILINE' to be an inline constant of type java.lang.String not a field expression in @editor.Annot
    private int d;
}

The JavaClass works as expected, but the GroovyClass gives these compiler errors (commented in the code). Not sure what is the problem.. How can I assign a string constant to an annotation value in groovy?

you have to access it by classname

import java.lang.annotation.*

@Target([ElementType.FIELD])
@Retention(RetentionPolicy.RUNTIME)
@interface Annot {
String value();
}

class GroovyClass {

    static final TEST_STRING = 'test'
    @Annot(GroovyClass.TEST_STRING) private int a;

    // FAILS static final TEST_GSTRING = "test$TEST_STRING"
    // FAILS @Annot(GroovyClass.TEST_GSTRING) private int b;

}

assert GroovyClass.getDeclaredField('a').annotations.first().value()==GroovyClass.TEST_STRING
// FAILS assert GroovyClass.getDeclaredField('b').annotations.first().value()==GroovyClass.TEST_GSTRING

Groovy 2.3

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