概述
Android中的注解(Annotations)可以修飾返回值或者方法參數(shù),加強(qiáng)編寫代碼時(shí)候的類型安全,在進(jìn)行代碼檢查的時(shí)候就能提示代碼潛在的問題。最常用的例子便是使用注解替換枚舉類型。相關(guān)資料可以參考Google官方文檔,或者我的翻譯文章
Google在Android應(yīng)用開發(fā)人員指南中不鼓勵(lì)使用枚舉類型:
枚舉類型比起靜態(tài)常量,需要消耗兩倍以上的內(nèi)存,請嚴(yán)格避免在Android上使用枚舉類型。
@IntDef
@IntDef是一種替換整數(shù)類型枚舉的方法,比如下面這個(gè)例子,我們記錄數(shù)據(jù)類型:
public class ItemTypeDescriptor {
public static final int TYPE_MUSIC = 0;
public static final int TYPE_PHOTO = 1;
public static final int TYPE_TEXT = 2;
public final int itemType;
public ItemTypeDescriptor(int itemType) {
this.itemType = itemType;
}
}
在上面代碼中,沒有任何的驗(yàn)證手段來確保傳給構(gòu)造函數(shù)的參數(shù)是符合要求的。這時(shí)候我們就可以使用@IntDef注解來確保傳遞數(shù)值的合法性。
public class ItemTypeDescriptor {
// ... type definitions
// Describes when the annotation will be discarded
@Retention(RetentionPolicy.SOURCE)
// Enumerate valid values for this interface
@IntDef({ TYPE_MUSIC, TYPE_PHOTO, TYPE_TEXT })
// Create an interface for validating int types
public @interface ItemTypeDef { }
// Mark the argument as restricted to these enumerated types
public ItemTypeDescriptor(@ItemTypeDef int itemType) {
this.itemType = itemType;
}
// get data
@ItemTypeDef
public int getItemType() {
return itemType;
}
}
現(xiàn)在用非法的參數(shù)調(diào)用構(gòu)造函數(shù),就會(huì)在Android Studio中提示錯(cuò)誤,因?yàn)榫幾g器明確的知道了所需要的數(shù)據(jù)類型。
@StringDef
@StringDef跟@IntDef類似,用來替換字符串類型的枚舉。
public class FilterColorDescriptor {
public static final String FILTER_BLUE = "blue";
public static final String FILTER_RED = "red";
public static final String FILTER_GRAY = "gray";
public final String filterColor;
public FilterColorDescriptor(String filterColor) {
this.filterColor = filterColor;
}
}
同上面的一樣,我們這里也用@StringDef來限定所傳入的數(shù)據(jù)類型
public class FilterColorDescriptor {
// ... type definitions
// Describes when the annotation will be discarded
@Retention(RetentionPolicy.SOURCE)
// Enumerate valid values for this interface
@StringDef({ FILTER_BLUE, FILTER_RED, FILTER_GRAY })
// Create an interface for validating int types
public @interface FilterColorDef { }
// Mark the argument as restricted to these enumerated types
public FilterColorDescriptor(@FilterColorDef String filterColor) {
this.filterColor = filterColor;
}
// get data
@FilterColorDef
public String getFilterColor() {
return filterColor;
}
}