JDK 1.5版本开始支持枚举类型,枚举类型使用关键字enum定义。
如果我们使用枚举类型来定义常量,会使代码更加易读并且安全,但性能上会差很多。枚举类型比普通常量类型的dex size 大 12倍以上(dex code 变大),运行时内存分配,一个enum值的声明会消耗20bytes以上,还不包括对象数组保持对enum值的引用。项目中大量使用enum,对内存影响不可忽视。
安卓官方文档已经提醒开发者尽量避免使用枚举类型,同时提供注解的方式检查类型安全,目前提供了int型和string型两种注解:IntDef和StringDef,用来提供编译期的类型检查。
http://developer.android.com/intl/zh-cn/training/articles/memory.html
public class Cat { public static final int MALE = 0; public static final int FEMALE = 1; private int sex; public void setSex(int sex) { this.sex = sex; } public String getSexDes() { if(sex == 0) { return "公"; }else if(sex == 1){ return "母"; }else { throw new IllegalArgumentException("Unkonw"); } } }
引入依赖包
compile 'com.android.support:support-annotations:22.0.0'
public class Cat { public static final int MALE = 0; public static final int FEMALE = 1; @IntDef({MALE, FEMALE}) @Retention(RetentionPolicy.SOURCE) public @interface SEX { } private int sex; public void setSex(@SEX int sex) { this.sex = sex; } public String getSexDes() { if(sex == 0) { return "公"; }else if(sex == 1){ return "母"; }else { throw new IllegalArgumentException("Unkonw"); } } }
@SEX注解可以放到属性定义,参数,返回值等地方对数据类型进行限制。如果随便赋值一个其他Int参数给setSex(),IDE会直接报错