Groovy 常量字符串作为注释值

标签 groovy

给定以下类(编辑器是包名称):

@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;
}

JavaClass 按预期工作,但 GroovyClass 给出了这些编译器错误(在代码中注释)。不确定问题是什么。如何将字符串常量分配给 groovy 中的注释值?

最佳答案

你必须通过类名访问它

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

关于Groovy 常量字符串作为注释值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24171860/

相关文章:

grails - Grails自动格式换行

groovy - 访问为 Jenkins Groovy 插件脚本指定的变量

xml - 如何在 Groovy 中通过标签名称查找所有 XML 元素?

java - 如何使用 ObjectWeb2 ASM 引导接口(interface)方法引用

grails - 我应该关闭 Grails 服务中的 groovy Sql

java - 如何在 Groovy 中设置最后一个字段

groovy - 安全导航运算符(operator) (?.) 不在 gradle 中工作?

Grails:将插件类导入到 _Events.groovy

java - Groovy/Spock 测试具有成员 @Inject 的 Java 类

api - 在 Groovy Soap UI 5.4.0 中执行类时出现 java.lang.InstantiationException 错误