views:

110

answers:

5

Hello,
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.

A: 

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.

Pointy
A: 

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

But you should be able to use the enum constants.

Stroboskop
A: 

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();
}
Bozho
thanks.. I cannot change the definition of annotation, so I guess you asserted that the usage is not possible!
bsreekanth
+5  A: 

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();
}
abhin4v
+3  A: 

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

}
matt b
+1 for the detailed example.. thanks
bsreekanth