android注解的原理 android注解框架



文章插图
android注解的原理 android注解框架

文章插图
Android官方不推荐使用枚举,因为使用枚举占用内存大,相比于静态常量Enum会花费两倍以上的内存 。因此就有另一种方式来替代枚举类的使用,[email protected]
枚举的理解
首先谈谈对枚举的理解,虽说平时用枚举不是很多,在某些情况下还是会用到枚举的 。
1、枚举是某个类的有限集合,它的对象个数不可由程序员增减,它的对象在一个枚举类生成的时候已经确定 。
2、枚举可以避免程序调用者使用了系统规定之外的变量,造成未知错误 。比如程序需要使用第三方SDK,传入了SDK未能处理的变量,造成SDK异常错误,如果使用了枚举,就可在编码时发现传入错误参数 。
@IntDef注解的使用
添加依赖:
implementation 'com.android.support:support-annotations:26.1.0'使用示例:
//方式一public class Test {//先定义 常量public static final int SUNDAY = 0;public static final int MONDAY = 1;public static final int TUESDAY = 2;public static final int WEDNESDAY = 3;public static final int THURSDAY = 4;public static final int FRIDAY = 5;public static final int SATURDAY = 6;//用 @IntDef "包住" 常量;// @Retention 定义策略// 声明构造器@IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})@Retention(RetentionPolicy.SOURCE)public @interface WeekDays {}@WeekDays private int currentDay = SUNDAY;public void setCurrentDay(@WeekDays int currentDay) {this.currentDay = currentDay;}@WeekDayspublic int getCurrentDay() {return currentDay;}} [email protected]({SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY})@Retention(RetentionPolicy.SOURCE)public @interface WeekDays {int SUNDAY = 0;int MONDAY = 1;int TUESDAY = 2;int WEDNESDAY = 3;int THURSDAY = 4;int FRIDAY = 5;int SATURDAY = 6;}[email protected]
[email protected],发现没有什么用,起不到限定作用,仍然可以随便传入值,测试代码如下:
@IntDef(WeekDays.SUNDAY,WeekDays.MONDAY,WeekDays.TUESDAY,WeekDays.WEDNESDAY,WeekDays.THURSDAY,WeekDays.FRIDAY,WeekDays.SATURDAY)@Retention(RetentionPolicy.SOURCE)annotation class WeekDays {companion object {const val SUNDAY = 0const val MONDAY = 1const val TUESDAY = 2const val WEDNESDAY = 3const val THURSDAY = 4const val FRIDAY = 5const val SATURDAY = 6}} class Test1 {private var currentDay = WeekDays.SUNDAY@WeekDaysfunget():Int = currentDayfun setCurrentDay(@WeekDays currentDay: Int){this.currentDay = currentDay}} fun main(arg:Array<String>){var test1 = Test1()test1.setCurrentDay(123)println(test1.get())}【android注解的原理 android注解框架】最终结果输出123 。