Iterate through values in @IntDef, @StringDef or any @Def class

A compromise can be made if we declare our fields within the @interface itself.

@Retention(RetentionPolicy.SOURCE)
@IntDef({MysteryFlags.NO_FLAGS, MysteryFlags.FIRST_FLAG, MysteryFlags.SECOND_FLAG, MysteryFlags.THIRD_FLAG, MysteryFlags.FOURTH_FLAG})
public @interface MysteryFlags {

    // Note that all fields declared in an interface are implicitly public static final
    int NO_FLAGS = ~0;
    int FIRST_FLAG = 1;
    int SECOND_FLAG = 1 << 1;
    int THIRD_FLAG = 1 << 2;
    int FOURTH_FLAG = 1 << 3;
}

When calling getFields() on MisteryFlags.class, all fields declared in the annotation are returned.

However, this means that any fields in the @interface that are not defined within the @IntDef will also be returned. IMO, this can work great if implemented by following a strict protocol.


I don't think you'll be able to query it like that at runtime. Your @MysterFlags annotation has a retention policy of SOURCE, which means it will be discarded by the compiler. Further, the @IntDef annotation has a retention policy of CLASS, which means it makes it through compile, but won't make it to runtime. That's why you are only seeing the @Retention annotation in your first loop (that annotation has a retention policy of RUNTIME).

Tags:

Java

Bitflags