Android限制参数传递之StringDef注解的使用

1. 引言

在参数传递时,如果你想限制传入的参数只能是特定的几个值,该怎么做呢?
除了把参数类型定义为枚举值,还可以使用注解来限制参数只能是你规定的几个值。以下3个注解就是起到了这样的作用:

  • @StringDef 限制参数只能是规定的几个String类型的值
  • @IntDef 限制参数只能是规定的几个Int类型的值
  • @LongDef 限制参数只能是规定的几个Long类型的值

2. 注解 @StringDef

@StringDef: 限制参数只能是规定的几个String类型的值。它作用到注解身上,接收你规定的几个字符串作为特定的值。

2.1 举例

在Java中,自定义注解 @ServiceName 来表示想要获取的系统服务的名字👇。

   @Retention(SOURCE)
   @StringDef({
        "power",
        "window",
        "layout_inflater"
   })
   public @interface ServiceName {
   } 

上面代码声明了 @ServiceName 注解,并且限制了被该注解修饰的参数只能是 “power”、“window”、“layout_inflater”。

接下来使用该注解,发挥作用!
比如,封装一个获取系统服务的方法,传入的参数为系统服务的名字。

   public Object getSystemService(@ServiceName String name) {
		// 省略...获取服务
   }																																										

外界在调用的时候,由于 String name 前面有@ServiceName 的修饰,因此只能传入 "power"、"window"、"layout_inflater" 这几个字符串。

否则的话,就会提示报错:👇
报错
包错信息已经很明显:传入的参数必须是 "power"、"window"、"layout_inflater"其中之一。


2.2 @StringDef源码解释

从 @StringDef 的源码也可以看出它的作用,下面是源码:👇

/**
 * Denotes that the annotated String element, represents a logical
 * type and that its value should be one of the explicitly named constants.
 * <p>
 * Example:
 * <pre><code>
 *  &#64;Retention(SOURCE)
 *  &#64;StringDef({
 *     POWER_SERVICE,
 *     WINDOW_SERVICE,
 *     LAYOUT_INFLATER_SERVICE
 *  })
 *  public @interface ServiceName {}
 *  public static final String POWER_SERVICE = "power";
 *  public static final String WINDOW_SERVICE = "window";
 *  public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
 *  ...
 *  public abstract Object getSystemService(@ServiceName String name);
 * </code></pre>
 */
@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface StringDef {
    /** Defines the allowed constants for this element */
    String[] value() default {};

    /**
     * Whether any other values are allowed. Normally this is
     * not the case, but this allows you to specify a set of
     * expected constants, which helps code completion in the IDE
     * and documentation generation and so on, but without
     * flagging compilation warnings if other values are specified.
     */
    boolean open() default false;
}

上文1.1 的举例,也是来源于源码注释中的举例。

3. 其他类似注解 @IntDef、@LongDef

与 @StringDef 注解类似,作用都是限制参数传递时,指定特定的几个值,防止外界传入不合理的值。区别是修饰的类型的不同,@IntDef、@LongDef分别代表了 Int 和 Long 类型。

这样在编译的阶段就能发现错误,而不是到运行时才出现预期之外的错误。

4. 总结

使用注解 @StringDef、@IntDef、@LongDef可以限制参数只能是规定的几个值,防止外界传入不合理的值。

这种用法是规范编程的体现,可以尝试用起来,让你的代码看起来专业而优雅。

感谢支持~

  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子林Android

感谢老板,老板大气!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值