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".
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
:
@interface SomeCustomAnnotation {
SomeDataProvider[] someValue()
}
And the processing to obtain SomeEnum[]
rather by calling:
methodg.getDeclaredAnnotation(SomeAnnotation.class)
.someValue()
.getSomeEnumArray();
You could also replace the SomeDataProvider
with an interface and make SomeAnnotation
take a java.lang.Class
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.