@IntDef的使用

android开发Enum (枚举)的完美替代 —— @IntDef的使用

4603人阅读 评论(0) 收藏 举报
分类:

     官方文档说明,安卓开发应避免使用Enum(枚举类),因为相比于静态常量Enum会花费两倍以上的内存。参 http://developer.android.com/training/articles/memory.html#Overhead

    那么如果需要使用Enum应该怎么做呢?

    https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/

  1. public class MainActivity extends Activity {  
  2.     
  3.     //先定义 常量  
  4.     public static final int SUNDAY = 0;  
  5.     public static final int MONDAY = 1;  
  6.     public static final int TUESDAY = 2;  
  7.     public static final int WEDNESDAY = 3;  
  8.     public static final int THURSDAY = 4;  
  9.     public static final int FRIDAY = 5;  
  10.     public static final int SATURDAY = 6;  
  11.     
  12.     //用 <span></span>@IntDef "包住" 常量;  
  13.     // @Retention 定义策略  
  14.     // 声明构造器  
  15.     @IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})  
  16.     @Retention(RetentionPolicy.SOURCE)  
  17.     public @interface WeekDays {}  
  18.     
  19.     @WeekDays int currentDay = SUNDAY;  
  20.     
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         setCurrentDay(WEDNESDAY);  
  26.     
  27.         //声明变量  
  28.         @WeekDays int today = getCurrentDay();  
  29.     
  30.         switch (today){  
  31.             case SUNDAY:  
  32.                 break;  
  33.             case MONDAY:  
  34.                 break;  
  35.             case TUESDAY:  
  36.                 break;  
  37.             case WEDNESDAY:  
  38.                 break;  
  39.             case THURSDAY:  
  40.                 break;  
  41.             case FRIDAY:  
  42.                 break;  
  43.             case SATURDAY:  
  44.                 break;  
  45.             default:  
  46.                 break;  
  47.         }  
  48.     
  49.     }  
  50.     
  51.     public void setCurrentDay(@WeekDays int currentDay) {  
  52.         this.currentDay = currentDay;  
  53.     }  
  54.     
  55.     @WeekDays  
  56.     public int getCurrentDay() {  
  57.         return currentDay;  
  58.     }  
  59. }  

使用注解库

这些注解不是默认加载的,它们被包装为一个单独的库。Support Library现在是由一些更小的库组成的,包括:v4-support、appcompat、gridlayout、mediarouter等等。
添加注解的最简单的方法就是打开Project Structure对话框。首先在左边选中module,然后右边选中Dependencies标签,点击“+”号按钮,选择Library Dependency。如果SDK中已经包括了Android Support库,那么注解支持库就会显示在快捷选择列表中了,只需要点击选择就可以。
06-13
<think>我们使用Android的`@IntDef`注解来替代枚举,以限制一个整型变量的取值范围。`@IntDef`是AndroidSupportAnnotations库(或Jetpack中的Annotation库)提供的一个元注解,用于在编译时检查整数值是否在指定的范围内。步骤:1.添加依赖(如果尚未添加):在build.gradle文件中添加:```groovydependencies{implementation'androidx.annotation:annotation:1.7.0'}```2.定义注解:使用`@IntDef`注解定义一个注解类型,其中列出允许的整数值。3.使用注解:在需要限制的整型变量(如方法参数、返回值、字段)上使用自定义的注解。4.验证取值:由于`@IntDef`仅在编译时进行静态检查,运行时无法直接验证。但我们可以通过编写工具方法在运行时检查。具体实现:###1.定义注解```javaimportandroidx.annotation.IntDef;//使用@IntDef定义允许的值publicclassStatus{//定义常量publicstaticfinalintSUCCESS=200;publicstaticfinalintNOT_FOUND=404;publicstaticfinalintSERVER_ERROR=500;//定义注解,限定取值@IntDef({SUCCESS,NOT_FOUND,SERVER_ERROR})@Retention(RetentionPolicy.SOURCE)//仅保留在源码中,编译后不保留public@interfaceStatusCode{}}```###2.使用注解```javapublicclassApiResponse{//使用注解限定字段@StatusCodeprivateintstatus;//使用注解限定参数publicvoidsetStatus(@StatusCodeintstatus){this.status=status;}@StatusCodepublicintgetStatus(){returnstatus;}}```###3.运行时验证(可选)由于`@IntDef`在编译后不会保留(通常使用`RetentionPolicy.SOURCE`),因此运行时无法通过反射获取允许的值。如果需要在运行时验证,可以单独定义一个验证方法:```javapublicclassStatusValidator{publicstaticbooleanisValidStatusCode(intcode){returncode==Status.SUCCESS||code==Status.NOT_FOUND||code==Status.SERVER_ERROR;}}```然后在设置值的地方调用:```javapublicvoidsetStatus(intstatus){if(!StatusValidator.isValidStatusCode(status)){thrownewIllegalArgumentException("Invalidstatuscode");}this.status=status;}```###4.使用示例```javaApiResponseresponse=newApiResponse();response.setStatus(Status.SUCCESS);//正确response.setStatus(400);//编译时可能不会报错(取决于IDE和注解处理器),但运行时会抛出异常(因为我们做了运行时检查)```###注意点:-**编译时检查**:使用AndroidStudio时,如果开启了注解处理,那么直接传入不在列表中的值会在编译时提示错误(或警告)。-**运行时检查**:由于`@IntDef`不保留到运行时,所以必须自己编写运行时验证逻辑(如果需要)。-**多个值**:`@IntDef`支持多个值,也可以使用`flag=true`表示按位或的组合值(类似标志位)。###使用@IntDef作为标志位(flag)```java@IntDef(flag=true,value={FLAG_A,FLAG_B,FLAG_C})@Retention(RetentionPolicy.SOURCE)public@interfaceFlags{}//使用publicvoidsetFlags(@Flagsintflags){...}```###总结使用`@IntDef`可以有效地在编译时限制整型变量的取值范围,同时避免了枚举带来的性能开销。但需要注意的是,它不提供运行时的验证,因此如果需要运行时验证,应额外编写验证逻辑。[^1]:[Android使用@IntDef和枚举enum限制元素取值范围的比较](https://blog.youkuaiyun.com/weixin_34349320/article/details/91466510)[^2]:[Android使用@IntDef注解替代枚举](https://blog.youkuaiyun.com/qq_17766199/article/details/78487800)§§相关问题§§1.如何在Kotlin中使用@IntDef注解?2.@IntDef和@StringDef有什么区别?3.如何在AndroidStudio中启用注解处理器?4.如何为@IntDef注解添加运行时保留策略?5.使用@IntDef注解时,如何同时支持多个值的组合?</think>在 Android 开发中,使用 `@IntDef` 注解替代枚举类可以有效限制整型变量的取值范围,同时避免枚举带来的性能开销(枚举会消耗约两倍的内存)[^1][^2]。以下是完整实现方案: ### 实现步骤 #### 1. 添加依赖 在 `build.gradle` 中添加注解库: ```groovy dependencies { implementation 'androidx.annotation:annotation:1.7.0' } ``` #### 2. 定义常量与注解 ```java import androidx.annotation.IntDef; public class StatusCodes { // 定义常量值 public static final int SUCCESS = 200; public static final int NOT_FOUND = 404; public static final int SERVER_ERROR = 500; // 定义@IntDef注解 @IntDef({SUCCESS, NOT_FOUND, SERVER_ERROR}) @Retention(RetentionPolicy.SOURCE) // 仅保留在源码级别 public @interface ValidStatusCode {} } ``` #### 3. 使用注解限制参数类型 ```java public class ApiHandler { // 使用注解限定参数范围 public void handleResponse(@StatusCodes.ValidStatusCode int statusCode) { // 业务逻辑... } } ``` #### 4. 运行时验证方法 ```java public class StatusValidator { // 检查值是否在允许范围内 public static boolean isValidStatusCode(int code) { return code == StatusCodes.SUCCESS || code == StatusCodes.NOT_FOUND || code == StatusCodes.SERVER_ERROR; } } // 使用示例 int inputCode = 404; if (StatusValidator.isValidStatusCode(inputCode)) { // 有效值处理 } else { throw new IllegalArgumentException("Invalid status code: " + inputCode); } ``` ### 关键优势与说明 1. **性能优势** `@IntDef` 在编译后会被擦除,仅保留 `int` 类型值,相比枚举节省约 2 倍内存[^1]。 2. **编译时检查** Android Studio 会在编译时检查注解使用: ```java // 正确使用 handler.handleResponse(StatusCodes.SUCCESS); // 编译错误:Must be one of: StatusCodes.SUCCESS, StatusCodes.NOT_FOUND... handler.handleResponse(400); ``` 3. **组合值支持(标志位)** ```java @IntDef(flag = true, value = { FLAG_READ, FLAG_WRITE, FLAG_EXECUTE }) public @interface FileModes {} ``` 4. **Kotlin 支持** 在 Kotlin 中使用更简洁: ```kotlin fun processCode(@StatusCodes.ValidStatusCode code: Int) { require(StatusValidator.isValidStatusCode(code)) } ``` ### 使用场景 - HTTP 状态码验证 - 错误代码范围限制 - 配置参数白名单 - 标志位组合验证 ### 注意事项 1. **运行时验证必要** 由于 `@Retention(RetentionPolicy.SOURCE)` 只在源码级别保留,运行时需显式验证[^2]。 2. **常量值管理** 所有允许值必须在同一类中定义为 `public static final int` 3. **IDE 支持** 确保启用注解处理(Android Studio > Preferences > Build > Annotations) [^1]: Android使用@IntDef和枚举enum限制元素取值范围的比较 [^2]: Android使用@IntDef注解替代枚举
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值