我們定義的類有一個(gè) int 型的狀態(tài)參數(shù)要設(shè)置抖韩,但我們設(shè)置的狀態(tài)又只能限定在[OPEN=1, CLOSE=2]這兩種狀態(tài)蛀恩,如果我們要提供一個(gè)接口來設(shè)置的話,那么一種做法是定義一個(gè)Enum枚舉來作為參數(shù)茂浮,這樣就能限定參數(shù)的取值范圍了双谆,但是使用枚舉會比常量占用更多的內(nèi)存。
這里可以用注解來處理這種問題席揽,也就是下面要講的自定義源碼注解顽馋,這里需要用到一個(gè)注解@IntDef,來看下代碼:
/**
* 測試源碼注解
*/
public class TestSourceAnnotation {
// 狀態(tài)值
public static final int STATUS_OPEN = 1;
public static final int STATUS_CLOSE = 2;
private static int sStatus = STATUS_OPEN;
private TestSourceAnnotation() {}
// 定義適用于參數(shù)的注解幌羞,限定取值范圍為{STATUS_OPEN, STATUS_CLOSE}
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PARAMETER)
@IntDef({STATUS_OPEN, STATUS_CLOSE})
public @interface Status {
}
/**
* 定義方法并使用@Status限定參數(shù)的取值
* @param status
*/
public static void setStatus(@Status int status) {
sStatus = status;
}
public static int getStatus() {
return sStatus;
}
public static String getStatusDesc() {
if (sStatus == STATUS_OPEN) {
return "打開狀態(tài)";
} else {
return "關(guān)閉狀態(tài)";
}
}
}
這里定義了一個(gè)@Status注解寸谜,并用注解@IntDef限定了取值范圍,最后將@Status注解用在參數(shù)上就行了属桦,這樣在調(diào)用方法時(shí)只能使用指定的參數(shù){STATUS_OPEN, STATUS_CLOSE}熊痴,就算用數(shù)值1編譯器也會提示報(bào)錯(cuò)他爸。除了@IntDef注解外還用一個(gè)@StringDef注解可以使用,用來處理字符串果善。
看下使用代碼:
/**
* 測試源碼注解
*/
private void _testSourceAnnotation() {
if (mIsOpen) {
// TestSourceAnnotation.setStatus(1); 直接設(shè)置數(shù)值編譯器會直接提示錯(cuò)誤
TestSourceAnnotation.setStatus(TestSourceAnnotation.STATUS_CLOSE);
mIsOpen = false;
} else {
TestSourceAnnotation.setStatus(TestSourceAnnotation.STATUS_OPEN);
mIsOpen = true;
}
mTvDesc.setText(TestSourceAnnotation.getStatusDesc());
}