Google开发者文档中说过
enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
即定义枚举会比定义静态常量多花费2倍以上的内存,那么想要限制他人使用特定的枚举值,又不使用枚举该怎么办么?
答案是使用@IntDef
,@StringDef
,使用这两个注解需要先在build.gradle中添加依赖:
compile 'com.android.support:support-annotations:25.0.1'
使用方法很简单,首先定义你需要的常量,然后用@IntDef
或@StringDef
包住这些常量,这样别人在使用你的方法时如果输入的值不在枚举的范围内,编译器就会给出提示了。
public static final int TYPE_MI = 1;
public static final int TYPE_MEIZU = 2;
public static final int TYPE_HUAWEI = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_MI, TYPE_MEIZU, TYPE_HUAWEI})
public @interface MOBILE_TYPE {
}
public static final String TYPE_HD = "720p";
public static final String TYPE_SHD = "1080p";
public static final String TYPE_FHD = "4k";
@Retention(RetentionPolicy.SOURCE)
@StringDef({TYPE_HD, TYPE_SHD, TYPE_FHD})
public @interface DISPLAY_TYPE {
}
public void doSomething(@MOBILE_TYPE int mobile, @DISPLAY_TYPE String display) {
}