在Android中如何使用注解取代Enum

在Android中如何使用注解取代Enum

Android中定义了许多的注解,如@IdRes,@LayoutRes…可以帮助我们在传递参数时,避免参数传递出错。当然我们也可以通过枚举定义参数,也可以达到相同效果。在Android中,系统为我们定义好了2个注解,@IntDef和@StringDef,具体代码如下所示:

Test类定义好注解

public class Test {

    public static final int A = 0;
    public static final int B = 1;
    public static final int C = 2;
    public static final int D = 3;
    public static final String E = "E";
    public static final String F = "F";
    public static final String G = "G";
    public static final String H = "H";

    @IntDef({A, B, C, D})
    @Retention(RetentionPolicy.SOURCE)
    public @interface FormatInt {

    }

    @StringDef({E, F, G, H})
    @Retention(RetentionPolicy.SOURCE) 
    public @interface FormatString {

    }
}
public class MainActivity extends AppCompatActivity {

   public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int format = getInt(Test.A);

        String f = getString(Test.E);

    }

    //在方法参数上使用注解
    public int getInt(@Test.FormatInt int format) {
        return format;
    }

    public String getString(@Test.FormatString String format) {
        return format;
    }
}

@IntDef注解的代码

@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface IntDef {
    /** Defines the allowed constants for this element */
    long[] value() default {};

    /** Defines whether the constants can be used as a flag, or just as an enum (the default) */
    boolean flag() default false;
}

@StringDef的注解代码

@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface StringDef {
    /** Defines the allowed constants for this element */
    String[] value() default {};
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值