Android annotation (2) use @IntDef instead of enumeration

We usually use annotations like this:

 private static WeekDay mCurrentDay;

    enum WeekDay {
        SUNDAY, MONDAY //12字节对象头+内容+8字节对齐
    }

    public static void setCurrentDay(WeekDay weekDay) {
        mCurrentDay = weekDay;
    }

We all know that enumerations are very memory intensive. Each enumeration instance is an Object object. Has 12-byte header + content + 8-byte alignment. We can use @IntDef instead:

 private static final int SUNDAY = 0;
    private static final int MONDAY = 1;
    @IntDef({SUNDAY,MONDAY})
    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.SOURCE)
    @interface WekDay {

    }
    private static int mCurrentIntDay;
    public static void setCurrentDay(@WekDay int currentDay){
        mCurrentIntDay = currentDay;
    }

Note that here @IntDef must enclose our defined constants.

If we use this call directly at this time:

setCurrentDay(1);

This will report an error.

In this case, you must use:

setCurrentDay(MONDAY);

Guess you like

Origin blog.csdn.net/howlaa/article/details/129699999