使用注解@IntDef替代枚举

开始之前我们先看看Android 官方文档中的一段话。
Be careful with code abstractions

Developers often use abstractions simply as a good programming practice, because 
abstractions can improve code flexibility and maintenance. However, abstractions 
come at a significant cost: generally they require a fair amount more code that 
needs to be executed, requiring more time and more RAM for that code to be mapped
into memory. So if your abstractions aren't supplying a significant benefit, you 
should avoid them.

For example, enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
官方的说法就是:我们在写代码的时候要注意类型的使用,以便于提高代码的扩展性和维护性,但是原型的使用一般会付出更多的内存的代价,所以如果没有特别大的好处,要尽量避免使用。对于枚举来说占用的内存往往是使用静态常量的两倍,因而我们要尽量避免在Android中使用枚举。
因而使用@IntDef注解来代替枚举是个不错的选择。
首先,添加android注解依赖:
compile 'com.android.support:support-annotations:25.1.0'
具体用法如下:
public class MainActivity extends AppCompatActivity{

  public static final int STATE_NONE = -1;
  public static final int STATE_LOADING = 0;
  public static final int STATE_SUCCESS = 1;
  public static final int STATE_ERROR = 2;
  public static final int STATE_EMPTY = 3;

  private @State int state;

  public void setState(@State int state){
      this.state = state;
  } 

  @State
  public int getState() {
    return this.state;
  }

  @IntDef({STATE_EMPTY, STATE_ERROR, STATE_LOADING, STATE_NONE, STATE_SUCCESS})
  @Retention(RetentionPolicy.SOURCE)
  public @interface State {
  }
}

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值