有没有办法将常量传递给 Groovy 中的注释? [英] Is there a way to pass a constant to an annotation in Groovy?

查看:31
本文介绍了有没有办法将常量传递给 Groovy 中的注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,可以将常量字符串作为参数传递给注释,但我不知道如何在 Groovy 中执行相同操作.

In Java, it's possible to pass a constant String as a parameter to an annotation, but I can't figure out how to do the same in 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    
        }
    }

在这里,方法 myMethod@MyGroovyAnnotation 注释,如果我传递一个字符串文字,如 @MyGroovyAnnotation(value="Something"),它工作得很好,但是如果我像上面的例子那样尝试传递 VALUE,我得到:

Here, where the method myMethod is annotated with @MyGroovyAnnotation, if I pass a String literal like @MyGroovyAnnotation(value="Something"), it works perfectly, but if I try to pass VALUE like in the example above, I get:

来自 Eclipse:

From Eclipse:

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

从 GroovyConsole 运行:

Running from 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

有没有人知道我需要做什么才能让它工作,或者是否有可能?感谢您提供的任何帮助或见解.

Does anybody have any idea what I need to do to get this to work, or if it's even possible? Thanks for any help or insight you can provide.

推荐答案

我遇到了同样的问题并且 Gerard 的回答有效,但我不需要创建一个新的 Constants 类,只需引用现有的类.

I ran into this same issue and Gerard's answer works, but I didn't need to make a new Constants class, just refer to the existing class.

>

例如:

@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 声望.

I wanted to leave a comment on the accepted answer, but I didn't have 50 reputation.

这篇关于有没有办法将常量传递给 Groovy 中的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆