Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typesafe enum in Java

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.

like image 353
bsr Avatar asked Mar 24 '26 10:03

bsr


2 Answers

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();
}
like image 121
Abhinav Sarkar Avatar answered Mar 25 '26 22:03

Abhinav Sarkar


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() {
        //...
    }

}
like image 43
matt b Avatar answered Mar 25 '26 22:03

matt b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!