首页 > 系统 > Android > 正文

在Android中使用Anntation来代替ENUM的方法

2019-10-22 18:14:36
字体:
来源:转载
供稿:网友

本文介绍了在Android中使用Anntation来代替ENUM的方法,分享给大家,具体如下:

如何代替

众所周知,在Android 开发中是不推荐使用java 中的ENUM 来编程的。因为ENUM 中每一个value 都会是一个Object 对象。跟常量的int和String 相比,占用的内存要大的多。

那么,如果我们在定义一些常量的时候,如何限制用户的输入呢? 举个例子:

如果用ENUM, 我们一般定义一年中的四个季节如下:

public enum Season{  SPRING, SUMMER, FALL, WINTER}

改用自定义常量的方式:

public class ConstantSeason {    public static final int SPRING = 1;  public static final int SUMMER = 2;  public static final int FALL = 3;  public static final int WINTER = 4;}

但是,这种使用常量的方式,存在一个问题,比如下面的方法

public void setSeason(int season)

你如何保证,使用者在使用这个方法时 传入的值是ConstantSeason.WINTER, ConstantSeason.SPRING, ConstantSeason.SUMMER,ConstantSeason.FALL 中的一个呢?

android 在Annotation 包中为我们提供一种注解的提示方法, 用法如下:

public class Season {    public static final int SPRING = 1;  public static final int SUMMER = 2;  public static final int FALL = 3;  public static final int WINTER = 4;  @IntDef({WINTER, SPRING, SUMMER, FALL})  @Retention(RetentionPolicy.SOURCE)  public @interface Season {  }  public void setSeason(@Season int season){    System.out.println("season" + season);  }}

当使用者,在调用setSeason 方法时, 如何传入的value , 不是WINTER, SPRING, SUMMER, FALL 中的一个。

AndroidStudio 会提示出错。

这样可以做到提醒开发人员这里的值,传入有问题。

结论

枚举至少比普通常量增加两倍于总体APK大小的字节,并且可以使用比等效常量多5至10倍的RAM内存。 为了优化apk性能问题, 建议使用Anntation 来代替ENUM.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表