Java中通过注解值获取枚举值

Moj*_*ojo 1 java enums annotations

我正在尝试使用与枚举值关联的注释字符串值,以获得对关联枚举值的引用。

我最终陷入了中途......目前我有以下开发代码:

注释代码:

public @interface MyCustomAnnotation{
    String value();
}
Run Code Online (Sandbox Code Playgroud)

枚举代​​码:

public enum MyEnum{
    @MyCustomAnnotation("v1")
    VALUE1,
    @MyCustomAnnotation("v2")
    VALUE2,
    @MyCustomAnnotation("v3")
    VALUE3,
}
Run Code Online (Sandbox Code Playgroud)

使用枚举注释:

String matchString = "v1";
MyEnum myEnumToMatch;

// First obtain all available annotation values
for(Annotation annotation : (MyEnum.class).getAnnotations()){
    // Determine whether our String to match on is an annotation value against
    // any of the enum values
    if(((MyCustomAnnotation)annotation).value() == matchString){
        // A matching annotation value has been found
        // I need to obtain a reference to the corrext Enum value based on
            // this annotation value
        for(MyEnum myEnum : MyEnum.values()){
            // Perhaps iterate the enum values and obtain the individual
                    // annotation value - if this matches then assign this as the
                    // value.
            // I can't find a way to do this - any ideas?
            myEnumToMatch = ??
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Mic*_*ers 5

在枚举中有一个字段会更容易,如下所示:

public enum MyEnum {
    VALUE1("v1"),
    VALUE2("v2"),
    VALUE3("v3");

    private String displayValue;

    private MyEnum(string s) {
        this.displayValue = s;
    }

    public String getDisplayValue() {
        return displayValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的匹配循环中,您只需循环MyEnum.values()并查找具有正确 displayValue 的那个。