Type Enumeration in Java

Not sure if the title is misleading, but the requirement is lower.

I need to use a string value as input for a custom annotation. When using the enum value, the IDE gives

The value of the java attribute must be constant.

@test("test") // works

@test(Const.myEnum.test.toString()) //java attribute value must be constant

I read about the importance of immutable string value. Is it possible to achieve the result through enum (and not public static final hacking of the string).

thank.

+3
source share
5 answers

If the annotation is inside your control, enter the attribute type enuminstead String. Otherwise, this is not possible.

, , java, (.. Test, Test):

// retention, target here
public @interface Test {
    YourEnum value();
}
+1

. :

@test(Const.myEnum.test)

, :

package Const;

public enum myEnum {
    test;
}

:

public @interface test {
    myEnum value();
}
+6

enum, , . , - .

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

}
+3

, , , String. - , , "toString" "" .

0

, toString()

But you should be able to use enumeration constants.

0
source

Source: https://habr.com/ru/post/1758011/


All Articles