案例
public class DiagonalLayoutSettings {
@Retention(SOURCE)
@IntDef({ BOTTOM, TOP, B_T})
public @interface Position {
}
public final static int LEFT = 1;
public final static int RIGHT = 2;
public final static int BOTTOM = 4;
public final static int TOP = 8;
public final static int B_T = 16;
@Retention(SOURCE)
@IntDef({ DIRECTION_LEFT, DIRECTION_RIGHT })
public @interface Direction {
}
public final static int DIRECTION_LEFT = 1;
public final static int DIRECTION_RIGHT = 2;
...
}
这里的@interface Position 和 public @interface Direction就是自己定义的注解.
//用注解去修饰方法参数.
public class DiagonalLayout extends FrameLayout {
DiagonalLayoutSettings settings;
public void setPosition(@DiagonalLayoutSettings.Position int position) {
settings.setPosition(position);
postInvalidate();
}
}
要控制setPosition方法的输入参数的合法性, 就可以使用注解来完成. 让这个方法只接收
public final static int LEFT = 1;
public final static int RIGHT = 2;
public final static int BOTTOM = 4;
public final static int TOP = 8;
public final static int B_T = 16;
这几个合法的int值.
调用方法
合法的调用:
setPosition(DiagonalLayoutSettings.TOP);
错误的非法调用:
setPosition(9);
编译器会给出错误提示:
Must be one of: DiagonalLayoutSettings.BOTTOM, DiagonalLayoutSettings.TOP, DiagonalLayoutSettings.B_T less... (⌃F1)
但会编译成功.
多使用这种设计模式非常的好.
---- DONE.----
网友评论
@Retention(SOURCE)
@IntDef({OK, JSON_FROMAT_ERROR, USER_NEED_LOGIN, USER_ACCOUNT_DELETE, USER_ACCOUNT_DELETE_FAILED_MONEY, USER_ACCOUNT_NOT_EXIT,
PURCHASE_BALANCE_NOT_SUFFICIENT, PURCHASE_ALREADY_BOUGHT, PURCHASE_FAILED, PURCHASE_PRODUCTION_ERROR, TIME_OUT,
TIME_INIT_FAILED, CANCEL, EMPTY, ERROR, AWARD_ALREADY_REWARD, DATA_STALE, OPERATION_FAILED, PERMISSION_DENIED,
DISCONNECTED, EXPIRED_TOKEN, INVALID_TOKEN, MAX_RETRIES, OVERRIDDEN_BY_SET, UNAVAILABLE, USER_CODE_EXCEPTION, NETWORK_ERROR,
WRITE_CANCELED, UNKNOWN_ERROR})
public @interface Code {
}
public final static int OK = 200;
public final static int JSON_FROMAT_ERROR = -400;
public final static int USER_NEED_LOGIN = 400;