IntDef 註釋
此註釋確保僅使用你期望的有效整數常量。
以下示例說明了建立註釋的步驟:
import android.support.annotation.IntDef;
public abstract class Car {
//Define the list of accepted constants
@IntDef({MICROCAR, CONVERTIBLE, SUPERCAR, MINIVAN, SUV})
//Tell the compiler not to store annotation data in the .class file
@Retention(RetentionPolicy.SOURCE)
//Declare the CarType annotation
public @interface CarType {}
//Declare the constants
public static final int MICROCAR = 0;
public static final int CONVERTIBLE = 1;
public static final int SUPERCAR = 2;
public static final int MINIVAN = 3;
public static final int SUV = 4;
@CarType
private int mType;
@CarType
public int getCarType(){
return mType;
};
public void setCarType(@CarType int type){
mType = type;
}
}
它們還使程式碼完成能夠自動提供允許的常量。
構建此程式碼時,如果 type 引數未引用其中一個已定義的常量,則會生成警告。