Android官方网不强烈推荐应用枚举,由于应用枚举占有运行内存大,对比于静态数据常量Enum会耗费二倍以上的运行内存。因而就会有另一种方式来取代枚举类的应用,那便是@IntDef注解。
枚举的了解
最先谈一谈对枚举的了解,虽然平常用枚举并不是许多,在某种情形下依然会使用枚举的。
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;
}
@WeekDays
public int getCurrentDay() {
return currentDay;
}
}
//方式二
@IntDef({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;
}
kotlin中应用@IntDef
在kotlin中使用@IntDef注解,发觉没什么用,起不上限制功效,依然可以随意传入值,测试代码如下所示:
@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 = 0
const val MONDAY = 1
const val TUESDAY = 2
const val WEDNESDAY = 3
const val THURSDAY = 4
const val FRIDAY = 5
const val SATURDAY = 6
}
}
class Test1 {
private var currentDay = WeekDays.SUNDAY
@WeekDays
fun get():Int = currentDay
fun setCurrentDay(@WeekDays currentDay: Int){
this.currentDay = currentDay
}
}
fun main(arg:Array<String>){
var test1 = Test1()
test1.setCurrentDay(123)
println(test1.get())
}
最后结论导出123。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。