Google開發(fā)者文檔中說過
enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
即定義枚舉會比定義靜態(tài)常量多花費2倍以上的內(nèi)存,那么想要限制他人使用特定的枚舉值,又不使用枚舉該怎么辦么笛谦?
答案是使用@IntDef
临扮,@StringDef
积蜻,使用這兩個注解需要先在build.gradle中添加依賴:
compile 'com.android.support:support-annotations:25.0.1'
使用方法很簡單试伙,首先定義你需要的常量,然后用@IntDef
或@StringDef
包住這些常量尤蛮,這樣別人在使用你的方法時如果輸入的值不在枚舉的范圍內(nèi)县匠,編譯器就會給出提示了风科。
public static final int TYPE_MI = 1;
public static final int TYPE_MEIZU = 2;
public static final int TYPE_HUAWEI = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_MI, TYPE_MEIZU, TYPE_HUAWEI})
public @interface MOBILE_TYPE {
}
public static final String TYPE_HD = "720p";
public static final String TYPE_SHD = "1080p";
public static final String TYPE_FHD = "4k";
@Retention(RetentionPolicy.SOURCE)
@StringDef({TYPE_HD, TYPE_SHD, TYPE_FHD})
public @interface DISPLAY_TYPE {
}
public void doSomething(@MOBILE_TYPE int mobile, @DISPLAY_TYPE String display) {
}