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

2018-12-15  本文已影响0人  zizi192

在android系统的源代码中,可以见到大量的注解,帮助开发者更方便也更规范的使用API接口。常见的注解包括@Override、@CallSuper、@NotNull、@Nullable、@AnyRes、@DrawableRes、@StringRes等。

今天要讲的是@IntDef和@StringDef,相对较少见到。以@IntDef为例,来说明其替代Enum的作用。

IntDef的定义

@IntDef是用来描述注解的注解,定义如下。根据释义可知,注解代表了一组合法的、显式说明的int常量。

/**
 * Denotes that the annotated element of integer type, represents
 * a logical type and that its value should be one of the explicitly
 * named constants. If the IntDef#flag() attribute is set to true,
 * multiple constants can be combined.
 * <p>
 * Example:
 * <pre><code>
 *  &#64;Retention(SOURCE)
 *  &#64;IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
 *  public @interface NavigationMode {}
 *  public static final int NAVIGATION_MODE_STANDARD = 0;
 *  public static final int NAVIGATION_MODE_LIST = 1;
 *  public static final int NAVIGATION_MODE_TABS = 2;
 *  ...
 *  public abstract void setNavigationMode(@NavigationMode int mode);
 *  &#64;NavigationMode
 *  public abstract int getNavigationMode();
 * </code></pre>
 * For a flag, set the flag attribute:
 * <pre><code>
 *  &#64;IntDef(
 *      flag = true,
 *      value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
 * </code></pre>
 */
@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface IntDef {
    /** Defines the allowed constants for this element */
    long[] value() default {};

    /** Defines whether the constants can be used as a flag, or just as an enum (the default) */
    boolean flag() default false;
}

Enum的使用

Enum是我们开发中常用的一种数据类型,可以表示一组限定范围内的常量,便于在编写和编译时进行查错。eg,针对性别类型,只有男、女两个值,但是如果使用静态常量时,不能保证入参的范围,Enum则可以解决这种问题。

Enum比常量占用了更多的内存,对内存资源宝贵的安卓应用来说,可以使用@IntDef+自定义注解来替代Enum的作用,同时解决Enum的高内存占用问题。

使用示例

    //定义仅支持本工厂、行业平均、其它值的类型。
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({INDUSTRY_TYPE_OTHER , INDUSTRY_TYPE_SELF, INDUSTRY_TYPE_AVERAGE})
    private  @interface INDUSTRY_TYPE{}

    public static final int INDUSTRY_TYPE_OTHER = 0;
    public static final int INDUSTRY_TYPE_SELF = 1;
    public static final int INDUSTRY_TYPE_AVERAGE = 2;

    //成员注解
    public @INDUSTRY_TYPE int type;//0:其它公司;1:本公司;2:行业平均
    //方法注解
    public void setType(@INDUSTRY_TYPE int type) {
        this.type = type;
    }

参考文档:
Android中不使用枚举类(enum)替代为@IntDef @StringDef

上一篇 下一篇

猜你喜欢

热点阅读