Iterate over values ​​in @IntDef, @StringDef or any @Def class

Consider this class:

public class MyClassOfMystery { public static final int NO_FLAGS = ~0; public static final int FIRST_FLAG = 1; public static final int SECOND_FLAG = 1 << 1; public static final int THIRD_FLAG = 1 << 2; public static final int FOURTH_FLAG = 1 << 3; @Retention(RetentionPolicy.SOURCE) @IntDef(flag = true, value = {NO_FLAGS, FIRST_FLAG, SECOND_FLAG, THIRD_FLAG, FOURTH_FLAG}) public @interface MysteryFlags { } ... set flags, get flags, and use flags stuff. } 

I often created something like this and found that it would be useful to be able to repeat all the flags available in MysteryFlags .

Can I MysteryFlags over the values ​​set in MysteryFlags ?

Here is what I tried:


Printed ANNOTATION: @java.lang.annotation.Retention(value=SOURCE) :

 for (Annotation annotation : Flag.class.getAnnotations()) { Log.d(TAG, String.format("ANNOTATION: %s", String.valueOf(annotation))); } 

This pushed NPE to zero array access.

 for (ExtraAction enm : Flag.class.getEnumConstants()) { Log.d(TAG, String.format("ENUM: %s", String.valueOf(enm))); } 

They did not print anything:

 for (Field field : Flag.class.getFields()) { Log.d(TAG, String.format("FIELD: %s", String.valueOf(field))); } 

and

 for (Class<?> aClass : ExtraAction.class.getClasses()) { Log.d(TAG, String.format("CLASS: %s", String.valueOf(aClass))); } 

I know that I can just add values ​​to the array and iterate over them, but for this I need to save another array. This is what I did, but still wondering if there is a better way.

+8
java bitflags
source share
2 answers

I don’t think you can request it the same way at runtime. Your @MysterFlags annotation has a SOURCE retention policy, which means that it will be discarded by the compiler. In addition, the @IntDef annotation has a CLASS retention policy, which means that it does it by compilation, but will not execute it at run time. That's why you only see the @Retention annotation in your first loop (the annotation has a RUNTIME retention RUNTIME ).

+8
source share

Well, that might be a little old, but I had a similar problem, and the solution I found was:

 MysteryFlags.class.getDeclaredFields() 

It will return all declared definitions.

0
source share

All Articles