加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

有没有办法将常量传递给Groovy中的注释?

发布时间:2020-12-14 16:35:12 所属栏目:大数据 来源:网络整理
导读:在 Java中,可以将常量String作为参数传递给注释,但是我无法弄清楚如何在Groovy中执行相同操作. 例如: @Retention(RetentionPolicy.RUNTIME) @Target(value=[ElementType.METHOD]) public @interface MyGroovyAnnotation { String value() } class MyGroovyC
在 Java中,可以将常量String作为参数传递给注释,但是我无法弄清楚如何在Groovy中执行相同操作.

例如:

@Retention(RetentionPolicy.RUNTIME)
    @Target(value=[ElementType.METHOD])
    public @interface MyGroovyAnnotation {
        String value()
    }

    class MyGroovyClass {

        public static final String VALUE = "Something"

        @MyGroovyAnnotation(value=VALUE)
        public String myMethod(String value) {
            return value    
        }
    }

在这里,如果我通过@MyGroovyAnnotation注释方法myMethod,如果我传递了一个像@MyGroovyAnnotation(value =“Something”)这样的字符串,那么它完美地工作,但如果我尝试像上面的例子中那样传递VALUE,我得到:

从Eclipse:

Groovy:Expected 'VALUE' to be an inline constant of type java.lang.String in @MyGroovyAnnotation

从GroovyConsole运行:

expected 'VALUE' to be an inline constant of type java.lang.String not a field expression in @MyGroovyAnnotation
 at line: 20,column: 31

Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' in @MyGroovyAnnotation
 at line: -1,column: -1

有没有人知道我需要做什么才能使这个工作,或者甚至可能吗?感谢您提供的任何帮助或洞察力.

解决方法

我遇到了同样的问题,而Gerard的回答也是这样,但是我不需要再创建一个常量类,只需要参考现有的类.

例如:

@Retention(RetentionPolicy.RUNTIME)
@Target(value=[ElementType.METHOD])
public @interface MyGroovyAnnotation {
    String value()
}

class MyGroovyClass {

    public static final String VALUE = "Something"

    @MyGroovyAnnotation(value=MyGroovyClass.VALUE)
    public String myMethod(String value) {
        return value    
    }
}

我想对接受的答案发表评论,但我没有50个声望.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读