注解代替枚举

都知道枚举在Android java 中使用会出现一些问题,使用多了还可能出现ANR异常,
但是很多时候不得不用,

在使用融云的时候自定义消息就是使用的这种方法

Java 中有@StringDef 和@intDef

public class BaseConst {
    public static final String TYPE_1 = "1";
    public static final String TYPE_2 = "2";
    @StringDef({TYPE_1, TYPE_2})
    public @interface Type {
    }
}


----------
public class BaseConst {
    public static final String TYPE_1 = 1;
    public static final String TYPE_2 = 2;
    @IntDef({TYPE_1, TYPE_2})
    public @interface Type {
    }
}

在使用的时候

//作为常量使用
@BaseConst.Type
public String type 

//作为方法使用
public void func(@BaseConst.Type String type){
//方法体
}
发布了96 篇原创文章 · 获赞 74 · 访问量 23万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章