开发者

Typesafe enum in Java

开发者 https://www.devze.com 2023-01-10 00:04 出处:网络
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

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 the annotation is within your control, make the attribute type be an enum type instead of String. Otherwise it is not possible.

Also, the annotation, as every java class, should start with upper-case (i.e. Test, not test):

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


If you want the annotation parameter to be restricted to values of an enum type, then give that type to the parameter, not String. An enum type is an enum type, and there's no way around the fact that calling "toString" is not a "constant" transformation.


The parameter must not be the result of a method, i.e. toString()

But you should be able to use the enum constants.

0

精彩评论

暂无评论...
验证码 换一张
取 消