Reputation: 53
I have made a custom annotation in java that takes one value (String[]);
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
String[] value ();
}
however, I want the values-when I use MyAnnotation-to be like this: aClassName.anAttribute
anAttribute is one of it's attributes which is a String:
public static String anAttribute1="aStringxxx";
But I get an error: The value for annotation attribute MyAnnotation.value must be a constant expression
Does anyone have an idea please?
Upvotes: 2
Views: 231
Reputation: 48045
If you make the attribute final
it will work just fine.
public class SomeClass {
public static final String myAttribute = "abc";
}
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String[] value();
}
public class SomeOtherClass {
@MyAnnotation({SomeClass.myAttribute})
private int someInt;
}
Upvotes: 2
Reputation: 3225
The solution is to mark anAttribute1
as a static final
to make it a constant expression.
class MyAttributeConstants {
public static final anAttribute1 = "someString";
}
Upvotes: 1
Reputation: 38122
I'm not sure if I understood your question correctly, but AFAIK you can not use constants which are defined in the same class that uses the annotation.
Possible solution: move the constants to a helper class
Upvotes: 0