遍历@ IntDef,@ StringDef或任何@Def类中的值 [英] Iterate through values in @IntDef, @StringDef or any @Def class

查看:85
本文介绍了遍历@ IntDef,@ StringDef或任何@Def类中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此类:

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

我经常创建类似这样的东西,并发现能够遍历 MysteryFlags 中所有可用的标志将很有用.

I have often created something like this, and found that it would be useful to be able to iterate through all flags available in MysteryFlags.

我可以遍历在 MysteryFlags 中设置的值吗?

Can I iterate through my values set in MysteryFlags?

这是我尝试过的:

此打印的注释:@ java.lang.annotation.Retention(value = SOURCE):

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


这将NPE置于空数组访问权限上


This threw NPE on a null Array access

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


这些没有打印出任何内容:


These did not print anything out:

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

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


我知道我可以将值添加到数组中并对其进行迭代,但这需要存储另一个数组.这是我所做的,但仍然想知道是否有更好的方法.


I know I can just add the values to an array and iterate through that, but that requires storing another array. It is what I have done, but still wonder if there is a better way.

推荐答案

我认为您无法在运行时像这样查询它.您的 @MysterFlags 批注的保留策略为 SOURCE ,这意味着它将被编译器丢弃.此外, @IntDef 批注的保留策略为 CLASS ,这意味着它是通过编译实现的,但不会进入运行时.这就是为什么您在第一个循环中仅看到 @Retention 批注的原因(该批注的保留策略为 RUNTIME ).

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).

这篇关于遍历@ IntDef,@ StringDef或任何@Def类中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆