简体   繁体   English

在Groovy批注中传递枚举数组

[英]Pass array of enums in Groovy annotation

I don't know why but I can't pass array to annotation which is declared as separated variable. 我不知道为什么,但是我无法将数组传递给声明为分隔变量的注释。

@Target([ ElementType.METHOD, ElementType.TYPE ])
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface SomeCustomAnnotation {

  SomeEnum[] someValue()
}

_ _

class SomeDataFactory {

static final SOME_ENUM_ARRAY = [SOME_ENUM_1, SOME_ENUM_2].toArray()

  enum SomeEnum {
   SOME_ENUM_1, SOME_ENUM_2
   }
}

_ _

class SomeClass {

   @SomeAnnotation(someValue = [SOME_ENUM_1, SOME_ENUM_2]) //fine
   def someMethod1(){}

   @SomeAnnotation(someValue = SOME_ENUM_ARRAY ) //Groovyc: Expected enum value for attribute someValue in @com.somepackage.SomeAnnotation
   def someMethod2(){}
}

Any ideas? 有任何想法吗?

Annotations expect inline constants. 注释需要内联常量。 So what you're trying to achieve cannot be done, even if variables are declared static and final.. 因此,即使将变量声明为静态和最终变量,也无法实现您要实现的目标。

Given that you're already using a separate class to provide the array, you can replace SomeAnnotation with its "provider". 假设您已经在使用单独的类来提供数组,则可以将SomeAnnotation替换为其“提供者”。

There are many ways to do this, but here is an example using a different enum: 有很多方法可以做到这一点,但是下面是使用不同枚举的示例:

enum SomeDataProvider {

    SOME_ENUM_ARRAY_PROVIDER([SOME_ENUM_1, SOME_ENUM_2]);

    private List<SomeAnnotation> array

    SomeDataProvider(def array) {
         this.array = array
    }

    public List<SomeAnnotation> getSomeEnumArray() {
       return array;
    }
}

Then change the code declaring the annotation to: 然后将声明注释的代码更改为:

@SomeAnnotation(someValue = SOME_ENUM_ARRAY_PROVIDER)
def someMethod2(){}

Of course, you would need to change the type expected by SomeCustomAnnotation : 当然,您需要更改SomeCustomAnnotation所需的类型:

@interface SomeCustomAnnotation {

  SomeDataProvider[] someValue()
}

And the processing to obtain SomeEnum[] rather by calling: 并通过调用以下代码获取SomeEnum[]的处理:

methodg.getDeclaredAnnotation(SomeAnnotation.class)
       .someValue()
       .getSomeEnumArray();

You could also replace the SomeDataProvider with an interface and make SomeAnnotation take a java.lang.Class object. 您也可以使用接口替换SomeDataProvider ,并使SomeAnnotation采用java.lang.Class对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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