将枚举元素分配给注释

时间:2014-12-17 12:33:17

标签: java enums attributes annotations

我想使用枚举元素作为注释属性的值(需要字符串值)。因此,我创建了一个包含String常量的接口:

public interface MyStringConstants {

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

此外,我创建了枚举:

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;
}

}

存在注释:

 @DeviceValidatorOperation(operationType=MyStringConstants.COMPANY_CONFIGURATION_READ)

我想定义上面提到的枚举,作为注释的operationType属性的值。使用上面的枚举结果就是这样:

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

导致Eclipse抱怨:

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

如何使用枚举元素作为注释属性的值?

0 个答案:

没有答案