在Android中如何使用注解取代Enum

来源:互联网 发布:caffe接口matlab 编辑:程序博客网 时间:2024/06/01 08:00

在Android中如何使用注解取代Enum

Android中定义了许多的注解,如@IdRes,@LayoutRes…可以帮助我们在传递参数时,避免参数传递出错。当然我们也可以通过枚举定义参数,也可以达到相同效果。在Android中,系统为我们定义好了2个注解,@IntDef和@StringDef,具体代码如下所示:

Test类定义好注解

public class Test {    public static final int A = 0;    public static final int B = 1;    public static final int C = 2;    public static final int D = 3;    public static final String E = "E";    public static final String F = "F";    public static final String G = "G";    public static final String H = "H";    @IntDef({A, B, C, D})    @Retention(RetentionPolicy.SOURCE)    public @interface FormatInt {    }    @StringDef({E, F, G, H})    @Retention(RetentionPolicy.SOURCE)     public @interface FormatString {    }}
public class MainActivity extends AppCompatActivity {   public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        int format = getInt(Test.A);        String f = getString(Test.E);    }    //在方法参数上使用注解    public int getInt(@Test.FormatInt int format) {        return format;    }    public String getString(@Test.FormatString String format) {        return format;    }}

@IntDef注解的代码

@Retention(SOURCE)@Target({ANNOTATION_TYPE})public @interface IntDef {    /** Defines the allowed constants for this element */    long[] value() default {};    /** Defines whether the constants can be used as a flag, or just as an enum (the default) */    boolean flag() default false;}

@StringDef的注解代码

@Retention(SOURCE)@Target({ANNOTATION_TYPE})public @interface StringDef {    /** Defines the allowed constants for this element */    String[] value() default {};}
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 残疾暴君的庶女妻 我在宗门种向日葵后拯救了修仙界 快穿:病娇男神又凶又粘人 戏精娘子总扮乖 我在系统圈中艰难生存 天道的疯批美人她靠算卦爆红 离婚后,偏执指挥官夜夜求关注 我靠无限物资全球基建 本道祖文成武德 全福夫人要和离 她从火光中来 裴先生每天都在撒娇求和 空间逃荒:团宠小尼姑路子野 别慌,学霸老爹和我一起穿越了 薄先生突然黏她上瘾 团宠崽崽是只桃花精 我那老板柔弱不能自理 反派小媳妇的逆袭指南 我有一个大佬群 二婚后,我在豪门扮柔弱 诸天仙神热搜:主神老婆竟是魔尊 团宠小福妻又娇又软 替嫁医妃有空间 重生之农门贵夫 野性偏爱 嫁给病弱太子后我躺赢了 咸鱼娘娘一心只想翻墙 救命!破产后高冷总裁处处招惹我 冷酷将军每天都想要贴贴 何以赎光 甜腻!病娇傅少竟然暗恋我! 天价萌妻:偏执帝少心尖宠 有读心术后,战神把娘子宠上天 穿书后,我刷错了反派的好感度 摄政王怀里的团宠美人娇又软 满级千金不想掉马 女帝她就是个卖药的! 华娱激荡年代 她来看我的演唱会 快穿:娇养反派大佬做替身 不努力种田就要和相公继承皇位了