使用注解代替枚举(enum)


概述:

enum在java中的实质是特殊单例的静态成员变量。在运行期,所有枚举类作为单例,全部加载到内存中。

所以,枚举增加了运行时的内存占用。


使用@IntDef/@StringDef + @interface来进行限定参数:

    @IntDef({ItemState.ADD, ItemState.SUCCESS, ItemState.LOADING, ItemState.FAIL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ItemState {
        int ADD = 0;
        int SUCCESS = 1;
        int LOADING = 2;
        int FAIL = 3;
    }

RetentionPolicy有3个值:CLASS  RUNTIME   SOURCE
用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;
用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时,

    private @ItemState int getState(int position) {
        final int actualItemCount = getActualItemCount();
        if ((actualItemCount < mMaxCount && (mLoadingViewIndex + mLoadingViewCount) < mMaxCount)
                && position == getItemCount() - 1) {
            return ItemState.ADD;
        } else if (isShowLoading(position)) {
            return ItemState.LOADING;
        } else if (position >= 0 && position < actualItemCount
                && FAIL_VIEW_PLACE_TEXT.equalsIgnoreCase(getItem(position))){
            return ItemState.FAIL;
        } else {
            return ItemState.SUCCESS;
        }
    }

 

public interface ILoginMethod {
    @IntDef({Method.OTHER, Method.ACCOUNT, Method.THIRD, Method.TOKEN, Method.MOBILE_CODE, Method.MOBILE_CMCC, Method.KG_FAST,
             Method.REGISTER, Method.CERTIFYCODE, Method.SMS})
    @Retention(RetentionPolicy.SOURCE)
    @interface Method {
        int OTHER = 0;
        int THIRD = 1;
        int ACCOUNT = 2;
        int TOKEN = 3;
        int MOBILE_CODE = 4;
        int KG_FAST = 5;
        int REGISTER = 6;
        int CERTIFYCODE = 7; // 扫脸认证成功后,通过token登录
        int MOBILE_CMCC = 8;    // 移动一键登录
        int SMS = 9;    // 短信验证码登录
    }
    void login();
    @Method int getMethod();
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM