Android中的枚举问题



在开发中我们时常要定义一些和后台约定好的字段来标识状态或者类别,比如订单状态,产品售卖状态,或者根据状态值去请求后台,如果如果直接使用1,2..会导致代码不好维护,全部都用public static final...设为常量,体现不了类别的关系,也不能自动检查检查传入的是否是合法的(Type Safety), 选择枚举,而Google官方却不建议这么来做,那...

为什么不用枚举呢,按照谷歌的说明是Enums often require more than twice as much memory as static constants,意思就是比使用常量多一倍的内存,但是根据一些实际的测试可能达到10多倍的内存。

谷歌推荐使用的注解的是形式来对应这种情况(既使用常量又能保证Type Safety), @IntDef, @StringDef分别对应整形常量和字符串常量。编译器在编写代码时给出代码提示及错误检查。

首先需要在build.gradle的dependencies下添加依赖支持:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    ...
    compile 'com.android.support:support-annotations:22.0.0'
}

DEMO:

public class MainActivity extends Activity {

    public static final int SUNDAY = 0;
    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;

    @IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
    @Retention(RetentionPolicy.SOURCE)
    public @interface WeekDays {}

    @WeekDays int currentDay = SUNDAY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setCurrentDay(WEDNESDAY);

        @WeekDays int today = getCurrentDay();

        switch (today){
            case SUNDAY:
                break;
            case MONDAY:
                break;
            case TUESDAY:
                break;
            case WEDNESDAY:
                break;
            case THURSDAY:
                break;
            case FRIDAY:
                break;
            case SATURDAY:
                break;
            default:
                break;
        }

    }

    public void setCurrentDay(@WeekDays int currentDay) {
        this.currentDay = currentDay;
    }

    @WeekDays
    public int getCurrentDay() {
        return currentDay;
    }
}

http://developer.android.com/intl/zh-cn/training/articles/memory.html#Overhead
https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/
http://v.youku.com/v_show/id_XMTMxOTM1NjY1Ng==.html
https://www.youtube.com/watch?v=Hzs6OBcvNQE
Android 中的 Enum 到底占多少内存?该如何用?