2

I would like to use an enum element as a value of an annotation attribute (which requires a string value). Hence, I have created an interface holding the String constants:

public interface MyStringConstants {

public static final String COMPANY_LOGIN = "Company Login";
public static final String COMPANY_LOGOUT = "Company Logout";
...
}

Furthermore I created the enum:

public enum MyEnumType implements MyStringConstants {

COMPANY_CONFIGURATION_READ(MyStringConstants.COMPANY_CONFIGURATION_READ), 
COMPANY_CONFIGURATION_WRITE(MyStringConstants.COMPANY_CONFIGURATION_WRITE), 
...; 

private final String value;

private MyEnumType(final String myStringConstant) {
    this.value = myStringConstant;
}

public String getValue() {
    return this.value.toString();
}

public static MyEnumType getByValue(final String value){
    for(final MyEnumType type : values()){
        if( type.getValue().equals(value)){
            return type;
        }
    }
    return null;
}

}

There exists an annotation:

 @DeviceValidatorOperation(operationType=MyStringConstants.COMPANY_CONFIGURATION_READ)

I would like to define the enum as mentioned above to put as a value for the annotation's operationType attribute. Using my enum from above results in this way:

@DeviceValidatorOperation(operationType=MyEnumType.COMPANY_CONFIGURATION_READ.getValue())

results in Eclipse complaining:

The value for annotation attribute DeviceValidatorOperation.operationType must be a constant expression

How can I achieve to use an enum element as a value for an annotation's attribute?

du-it
  • 2,561
  • 8
  • 42
  • 80
  • You have to use the EnumType as `operationType` not the value of it. – Jens Dec 17 '14 at 12:39
  • 1
    Annotations are baked in at compile time, hence why you can only use constants, you could pass string in instead MyStringConstants.COMPANY_CONFIGURATION_READ – Adam Dec 17 '14 at 12:39
  • what is the type of `operationType`? – dsharew Dec 17 '14 at 12:40
  • operationType is of type String. – du-it Dec 17 '14 at 14:18
  • I can't use the MyEnumType itself as value for operationType because it is defined as String (not as MyEnumType). – du-it Dec 17 '14 at 14:19
  • 1
    possible duplicate of [How to supply Enum value to an annotation from a Constant in Java](http://stackoverflow.com/questions/13253624/how-to-supply-enum-value-to-an-annotation-from-a-constant-in-java) – Martin Schröder Jul 31 '15 at 12:36

0 Answers0