1

関連付けられた列挙値への参照を取得するために、列挙値に関連付けられた注釈文字列値を使用しようとしています。

途中で行き詰まってしまいました...現在、以下の開発コードがあります。

注釈コード:

public @interface MyCustomAnnotation{
    String value();
}

列挙コード:

public enum MyEnum{
    @MyCustomAnnotation("v1")
    VALUE1,
    @MyCustomAnnotation("v2")
    VALUE2,
    @MyCustomAnnotation("v3")
    VALUE3,
}

enum アノテーションを利用する:

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 = ??
        }
    }
}

前もって感謝します。

4

3 に答える 3

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

次に、一致するループで、ループして正しいdisplayValueを持つループをMyEnum.values()探します。

于 2013-02-21T15:38:40.293 に答える
2

注釈を使用するよりも、列挙型に値を追加する方が良いという@MichaelMyersに完全に同意します。ただし、以下のコードは、注釈が列挙値にどのように付加されるかを理解するのに役立ちます。

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
    String value();
}

public enum Example {
    @MyAnno("v1")   FOO, 
    @MyAnno("v2")   BAR, 
    @MyAnno("v3")   BAZ
}


public static void main(String[] argv)
throws Exception {
    for (Field field : Example.class.getDeclaredFields()) {
        System.out.println(field.getName());
        for (Annotation anno : field.getAnnotations()) {
            if (anno instanceof MyAnno) {
                MyAnno myAnno = (MyAnno)anno;
                System.out.println("   anno = " + myAnno.value());
            }
        }
    }
}
于 2013-02-21T15:43:59.007 に答える
1

列挙定数はクラスの通常のフィールドであるenumため、リフレクションを介してアクセスする必要があります。

for (Field enumValue : MyEnum.class.getDeclaredFields()) {
    MyAnnotation annotation = enumValue.getAnnotation(MyAnnotation.class);
    if (annotation != null) {
        System.out.printf("Field '%s' is annotated with @MyAnnotation with value '%s'\n",
                enumValue.getName(),
                annotation.value());
    } else {
        System.out.printf("Field '%s' is not annotated with @MyAnnotation\n", enumValue.getName());
    }
}

これには、$VALUESすべての列挙値を含む配列を含む と呼ばれる内部フィールドも含まれます。たとえば、を使用してそれを除外できますif (enumValue.isSynthethic()) { ... }

于 2013-02-21T15:54:14.517 に答える