注解@IntDef 替换 Emum

作者: Candy有雪吃 | 来源:发表于2018-08-10 13:19 被阅读13次

我们定义的类有一个 int 型的状态参数要设置,但我们设置的状态又只能限定在[OPEN=1, CLOSE=2]这两种状态,如果我们要提供一个接口来设置的话,那么一种做法是定义一个Enum枚举来作为参数,这样就能限定参数的取值范围了,但是使用枚举会比常量占用更多的内存。
这里可以用注解来处理这种问题,也就是下面要讲的自定义源码注解,这里需要用到一个注解@IntDef,来看下代码:

    /**
     * 测试源码注解
     */
    public class TestSourceAnnotation {
     
        // 状态值
        public static final int STATUS_OPEN = 1;
        public static final int STATUS_CLOSE = 2;
     
        private static int sStatus = STATUS_OPEN;
     
     
        private TestSourceAnnotation() {}
     
     
        // 定义适用于参数的注解,限定取值范围为{STATUS_OPEN, STATUS_CLOSE}
        @Retention(RetentionPolicy.SOURCE)
        @Target(ElementType.PARAMETER)
        @IntDef({STATUS_OPEN, STATUS_CLOSE})
     
        public @interface Status {
        }
     
        /**
         * 定义方法并使用@Status限定参数的取值
         * @param status
         */
        public static void setStatus(@Status int status) {
            sStatus = status;
        }
     
        public static int getStatus() {
            return sStatus;
        }
     
     
        public static String getStatusDesc() {
            if (sStatus == STATUS_OPEN) {
                return "打开状态";
            } else {
                return "关闭状态";
            }
        }
    }

这里定义了一个@Status注解,并用注解@IntDef限定了取值范围,最后将@Status注解用在参数上就行了,这样在调用方法时只能使用指定的参数{STATUS_OPEN, STATUS_CLOSE},就算用数值1编译器也会提示报错。除了@IntDef注解外还用一个@StringDef注解可以使用,用来处理字符串。

看下使用代码:

/**
 * 测试源码注解
 */
private void _testSourceAnnotation() {
    if (mIsOpen) {
//            TestSourceAnnotation.setStatus(1); 直接设置数值编译器会直接提示错误
        TestSourceAnnotation.setStatus(TestSourceAnnotation.STATUS_CLOSE);
        mIsOpen = false;
    } else {
        TestSourceAnnotation.setStatus(TestSourceAnnotation.STATUS_OPEN);
        mIsOpen = true;
    }
 
    mTvDesc.setText(TestSourceAnnotation.getStatusDesc());
}

相关文章

  • 注解@IntDef 替换 Emum

    我们定义的类有一个 int 型的状态参数要设置,但我们设置的状态又只能限定在[OPEN=1, CLOSE=2]这两...

  • Android 常用注解

    Nullness注解 资源注解 资源注解的Target都是PARAMETER 类型定义注解@IntDef 使用情景...

  • 性能

    @IntDef替代枚举 @IntDef/@StringDef本身是个Android中提供的一种注解. 添加依赖:c...

  • 替代枚举的注解

    Android中新引入的替代枚举的注解有IntDef和StringDef,这里以IntDef做例子说明一下.

  • Android 常用注解介绍及注解声明

    一、常用注解 开发中经常使用到注解,例如Android自带的 IntDef、StringDef、NonNull、N...

  • 查阅资料

    @IntDef的使用(替代枚举) 注解: java 集合 [https://blog.csdn.net/zhang...

  • 注解代替枚举案例 2019-01-25

    title: 注解代替枚举案例 20180312 参考: @IntDef的使用(替代枚举) 使用情形:比如 对 a...

  • Android中代替枚举的@IntDef用法

    IntDef本身是个Android中提供的一种注解,用于替代枚举的使用 定义static final的常量 定义一...

  • 注解杂记

    前言 在阅读源码的时候,经常会遇到一些以前没见过的注解,所以开了个坑记一下笔记。 @IntDef 这个注解在许多源...

  • @IntDef,@StringDef注解使用-替代Enum

    在android系统的源代码中,可以见到大量的注解,帮助开发者更方便也更规范的使用API接口。常见的注解包括@Ov...

网友评论

    本文标题:注解@IntDef 替换 Emum

    本文链接:https://www.haomeiwen.com/subject/dsmkbftx.html