![](/img/trans.png)
[英]Eclipse compiler says attribute is undefined in case of array of enums field in the annotation
[英]Pass array of enums in Groovy annotation
我不知道为什么,但是我无法将数组传递给声明为分隔变量的注释。
@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(){}
}
有任何想法吗?
注释需要内联常量。 因此,即使将变量声明为静态和最终变量,也无法实现您要实现的目标。
假设您已经在使用单独的类来提供数组,则可以将SomeAnnotation
替换为其“提供者”。
有很多方法可以做到这一点,但是下面是使用不同枚举的示例:
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;
}
}
然后将声明注释的代码更改为:
@SomeAnnotation(someValue = SOME_ENUM_ARRAY_PROVIDER)
def someMethod2(){}
当然,您需要更改SomeCustomAnnotation
所需的类型:
@interface SomeCustomAnnotation {
SomeDataProvider[] someValue()
}
并通过调用以下代码获取SomeEnum[]
的处理:
methodg.getDeclaredAnnotation(SomeAnnotation.class)
.someValue()
.getSomeEnumArray();
您也可以使用接口替换SomeDataProvider
,并使SomeAnnotation
采用java.lang.Class
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.