在没有@IntDef和@StringDef之前,对于一些常量值的维护和使用是一个困扰,到底是用enum还是静态常量呐。用静态常量只能是固定常量值,对于需要需一个范围值来说不适合,但是用enum对于内存消耗又是一个问题:Android官方文档中也有说明,enum中的每一个值其实都是一个Object对象,每声明一个值就会创建一部分的内存以使它能够被引用到这个对象,相比于静态常量,enum会花费近2倍的内存空间。
google也考虑到这点了,因此推荐大家使用@IntDef和@StringDef来代替enum问题完美解决:简单说下如何使用:
1.在gradle里面添加依赖:
implementation 'com.android.support:support-annotations:28.0.0'
2.定义接口:
public class DemoDef { public static final int DEMO_ONE = 1; public static final int DEMO_TWO = 2; public static final int DEMO_THREE = 3; @IntDef({DEMO_ONE, DEMO_TWO, DEMO_THREE}) @Retention(RetentionPolicy.SOURCE) public @interface Test { } public @Test static int value; public static void setType(@Test int type) { value= type; } public static int getType() { return value; } }
定义了一个Test接口并添加了两个注解,一个set和get方法.特别注意在调用setType时,只能是@IntDef里面的值,其余都会报错.