Android 中巧妙使用枚举类型

Android 中巧妙使用枚举类型

众所周知,在Android中并不推荐使用枚举类型,来听听官方的说法:

Android Developer-Avoid enumerations
Avoid enumerations
A single enum can add about 1.0 to 1.4 KB of size to your app’s classes.dex file. These additions can quickly accumulate for complex systems or shared libraries. If possible, consider using the @IntDef annotation and ProGuardto strip enumerations out and convert them to integers. This type conversion preserves all of the type safety benefits of enums.

翻译:每个枚举常量可以使你的应用程序的classes.dex文件增加大约1.0到1.4 KB的大小。 这些额外增加的占用会迅速在你的系统或共享库中累加。如果可能的话Android中推荐使用@IntDef 注解或ProGuard代替。

虽不建议使用枚举类,官方给出了另一种解决方案,那就是使用@IntDef、@StringDef。这种方式比枚举类的写法复杂一点,但并没有什么难度。请看例子说明:

  1. 创建一个Interface文件

    import androidx.annotation.StringDef;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    @StringDef({BookType.TYPE_COMIC, BookType.TYPE_FICTION, BookType.TYPE_STORE})
    public @interface BookType {
        public static final String TYPE_COMIC = "comic";
        public static final String TYPE_FICTION = "fiction";
        public static final String TYPE_STORE = "store";
    }
    

    这就是Android官方推荐的替代传统枚举的方法,不要忘了Interface前面有@。

  2. 其次,如何使用?

    public Book getBook(@BookType String type) {
        Book book = null;
        if (type == BookType.TYPE_COMIC) {
            /* 操作 */
        } else if (type == BookType.TYPE_FICTION) {
            /* 操作 */
        } else if (type == BookType.TYPE_STORE) {
            /* 操作 */
        }
        return book;
    }
    
    
    public class Book {
    
        public Book(@BookType String type) {
    
        }
    }
    

    可以看出,使用的方法跟传统枚举差不多!


简单小分享 日期:2020-05-12

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值