Not sure whether the title is misleading, but requirement is below.
I need to use a string value as input to a custom annotation. When use an enum value, the IDE gives
java attribute value must be constant.
@test("test") // works
@test(Const.myEnum.test.toString()) //java attribute value must be constant
I read about the importance of the string value being immutable. Is it possible to achive through enum (not the public static final String hack).
thanks.
Enums can be used in annotations. You should do it like this:
@test(Const.myEnum.test)
assuming you have defined an enum like this:
package Const;
public enum myEnum {
test;
}
and the annotation like this:
public @interface test {
myEnum value();
}
There shouldn't be any problem using an enum, the issue might be with how you are declaring it or the annotation. Here is an example that compiles without any issue.
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface MyAnnotation {
MyEnum value();
public enum MyEnum {
ONE, TWO, THREE, FOUR
}
}
public class AnnotationTest {
@MyAnnotation(MyEnum.ONE)
public void someMethod() {
//...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With