用注解替换枚举

概述


Android中的注解(Annotations)可以修饰返回值或者方法参数,加强编写代码时候的类型安全,在进行代码检查的时候就能提示代码潜在的问题。最常用的例子便是使用注解替换枚举类型。相关资料可以参考Google官方文档,或者我的翻译文章

Google在Android应用开发人员指南中不鼓励使用枚举类型:

枚举类型比起静态常量,需要消耗两倍以上的内存,请严格避免在Android上使用枚举类型。

@IntDef


@IntDef是一种替换整数类型枚举的方法,比如下面这个例子,我们记录数据类型:

public class ItemTypeDescriptor {
    public static final int TYPE_MUSIC = 0;
    public static final int TYPE_PHOTO = 1;
    public static final int TYPE_TEXT = 2;

    public final int itemType;

    public ItemTypeDescriptor(int itemType) {
        this.itemType = itemType;
    }
}

在上面代码中,没有任何的验证手段来确保传给构造函数的参数是符合要求的。这时候我们就可以使用@IntDef注解来确保传递数值的合法性。

public class ItemTypeDescriptor {
    // ... type definitions
    // Describes when the annotation will be discarded
    @Retention(RetentionPolicy.SOURCE)
    // Enumerate valid values for this interface
    @IntDef({ TYPE_MUSIC, TYPE_PHOTO, TYPE_TEXT })
    // Create an interface for validating int types
    public @interface ItemTypeDef { }
    // Mark the argument as restricted to these enumerated types
    public ItemTypeDescriptor(@ItemTypeDef int itemType) {
        this.itemType = itemType;
    }
    
    // get data
      @ItemTypeDef
      public int getItemType() {
        return itemType;
      }
}

现在用非法的参数调用构造函数,就会在Android Studio中提示错误,因为编译器明确的知道了所需要的数据类型。

@StringDef


@StringDef@IntDef类似,用来替换字符串类型的枚举。

public class FilterColorDescriptor {
    public static final String FILTER_BLUE = "blue";
    public static final String FILTER_RED = "red";
    public static final String FILTER_GRAY = "gray";

    public final String filterColor;

    public FilterColorDescriptor(String filterColor) {
        this.filterColor = filterColor;
    }
}

同上面的一样,我们这里也用@StringDef来限定所传入的数据类型

public class FilterColorDescriptor {
    // ... type definitions
    // Describes when the annotation will be discarded
    @Retention(RetentionPolicy.SOURCE)
    // Enumerate valid values for this interface
    @StringDef({ FILTER_BLUE, FILTER_RED, FILTER_GRAY })
    // Create an interface for validating int types
    public @interface FilterColorDef { }
    // Mark the argument as restricted to these enumerated types
    public FilterColorDescriptor(@FilterColorDef String filterColor) {
        this.filterColor = filterColor;
    }
    
    // get data
      @FilterColorDef
      public String getFilterColor() {
        return filterColor;
      }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容