用support annotation替代enum

一次演讲中听到android中使用enum可能会造成很大的性能问题。开始我是怀疑的。为什么怀疑?因为我在好几个地方用到了枚举类型。再去查看过谷歌的API,enum的直接子类也有好多,比如:

Allocation.MipmapControl,
Authenticator.RequestorType,
AvoidXfermode.Mode,
Bitmap.CompressFormat,
Bitmap.Config, BlurMaskFilter.Blur,
Canvas.EdgeType,
Canvas.VertexMode,
ClientInfoStatus,
ConsoleMessage.MessageLevel,
CursorJoiner.Result,
and 48 others.

简单看了下,Android还是有好多地方使用了。那为什么还不建议使用呢?查了一番,看到google官方有一段关于enum使用的介绍。既然使用不当可能会导致性能问题,那我们怎么办呢?

这里介绍下Support包中的annotation,使用 @IntDef@StringDef 来达到我们枚举的效果。由于@IntDef 的介绍比较多,这里给个@StringDef 的Demo:

public class MyClient {
    public static final String ONE = "one";
    public static final String RECORD = "record";
    public static final String STATUS = "status";

    @StringDef({ONE, RECORD, STATUS})
    public @interface Client {
    }

    private String mClient;

    public MyClient(@Client String client) {
        mClient = client;
    }
    ...
}

这样,在外面创建MyClient对象的时候,构造方法中传入的参数就必须为 ONE, RECORD, STATUS 其中之一,从而达到类似enum的效果。


参考:

  1. https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/
  2. The price of ENUMs
  3. http://tools.android.com/tech-docs/support-annotations
  4. http://developer.android.com/reference/java/lang/Enum.html
  5. http://stackoverflow.com/questions/29183904/should-i-strictly-avoid-using-enums-on-android
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值