欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android 代替枚举

程序员文章站 2022-05-21 08:18:17
...

核心工具:IntDef和StringDef官方注解

compile 'com.android.support:support-annotations:22.0.0'

原理:编译期的类型检查

定义:

    public static final int Relationship_User = 0;// 陌生人
    public static final int Relationship_Friend = 1;// 通讯录好友
    public static final int Relationship_Requesting = 2;// 已发送好友请求
    @IntDef({Relationship_User, Relationship_Friend,Relationship_Requesting})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Relationship {
    }

使用

    @Relationship
    private int relationship;

    @Relationship
    public int getRelationship() {
        return relationship;
    }

    public void setRelationship(@Relationship int relationship) {
        this.relationship = relationship;
    }
    
    void xxx(){
        this.setRelationship(1);// 有警告
        if (this.getRelationship() == 1){}// 有警告

        this.setRelationship(Relationship_User);// 没有
        if (this.getRelationship() == Relationship_User);// 没有
    }

完整的代码如下

    public class KapModelMessage extends KapModelBase {
    public static final int Relationship_User = 0;// 陌生人
    public static final int Relationship_Friend = 1;// 通讯录好友
    public static final int Relationship_Requesting = 2;// 已发送好友请求
    @IntDef({Relationship_User, Relationship_Friend,Relationship_Requesting})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Relationship {
    }
    @Relationship
    private int relationship;

    @Relationship
    public int getRelationship() {
        return relationship;
    }

    public void setRelationship(@Relationship int relationship) {
        this.relationship = relationship;
    }

    void xxx(){
        this.setRelationship(1);// 有警告
        if (this.getRelationship() == 1){}// 有警告

        this.setRelationship(Relationship_User);// 没有
        if (this.getRelationship() == Relationship_User);// 没有
    }
}