Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
很多開發規範都是不建議在Android中使用枚舉的,在Android系統中使用枚舉的開銷是使用常量的2倍。一般地,在一個檔案中定義常量
public class FileType {
public static final int TYPE_MUSIC = 0;
public static final int TYPE_PHOTO = 1;
public static final int TYPE_TEXT = 2;
public final int fileType;
public FileType(int fileType) {
this.fileType = fileType;
}
}
但這樣的定義會有一定有小問題。就是這個類在給他人使用時,構造函數由于參數是
int
類型。是以他可以傳遞我們定義好的3種類型中的其它任意
int
數值,這就有可能會産生某種錯誤。我們希望 當使用者輸入了我們定義之外的數值,編輯器可以給我們提示。下面我們就看看
android.support.annotation
包中提供的注解幫我們解決這個問題。
@IntDef
我們先看用法,使用上面的例子
public class FileType {
public static final int TYPE_MUSIC = 0;
public static final int TYPE_PHOTO = 1;
public static final int TYPE_TEXT = 2;
public final int fileType;
//Retention 是元注解,簡單地講就是系統提供的,用于定義注解的“注解”
@Retention(RetentionPolicy.SOURCE)
//這裡指定int的取值隻能是以下範圍
@IntDef({TYPE_MUSIC, TYPE_PHOTO, TYPE_TEXT})
@interface FileTypeDef {
}
public FileType(@FileTypeDef int fileType) {
this.fileType = fileType;
}
}
@Retention
是元注解,簡單地講就是系統提供的,用于定義注解的“注解”。使用這個辨別了注解的生命周期,這裡指定值為
RetentionPolicy.SOURCE
說明這個注解保留在源碼階段。還有
RetentionPolicy.RUNTIME
,
RetentionPolicy.CLASS
分别表示這個注解保留到運作時,和位元組碼階段。
我們這裡使用
RetentionPolicy.SOURCE
的用意就是在編碼時能夠識别出錯誤的
FileType
,至于
RUNTIME
和
CLASS
階段的狀态,我們是不關心的。
@IntDef
是
android.support.annotation
包定義的注解,使用它來規範我們的
fileType
變量的取值範圍。例如在構造函數中使用
FileType(@FileTypeDef int fileType)
表示
fileType
的取值隻能是
TYPE_MUSIC,TYPE_PHOTO,TYPE_TEXT
。
如果在傳參時沒有按照指定的值那麼編輯器就會發出警告,這樣就可以在編碼的時候進行提示。
@StringDef
同樣地,還可以對字元串常量定義注解。例如對于以下檔案
public class FileType {
public static final String TYPE_MUSIC = "mp3";
public static final String TYPE_PHOTO = "png";
public static final String TYPE_TEXT = "txt";
public final String fileType;
public FileType(String fileType) {
this.fileType = fileType;
}
}
使用
@StringDef
注解
public class FileType {
//...類型定義
public final String fileType;
//Retention 是元注解,簡單地講就是系統提供的,用于定義注解的“注解”
@Retention(RetentionPolicy.SOURCE)
//這裡指定int的取值隻能是以下範圍
@StringDef({TYPE_MUSIC, TYPE_PHOTO, TYPE_TEXT})
@interface FileTypeDef {
}
public FileType(@FileTypeDef int fileType) {
this.fileType = fileType;
}
}
使用注解除了可以避免不必要錯誤外,還能瞬間*提升自己寫代碼的 Level *。
有木有?
微信關注我們,可以擷取更多
