Android 包android.support.annotation包提供了諸如 @IntDef 和 @StringDef 等注解归形,可以讓AS, Lint 提供靜態(tài)代碼檢查功能
用注解型枚舉代替普通靜態(tài)常量和枚舉
原因:
- 枚舉銷毀的內(nèi)存是普通靜態(tài)常量的兩倍
- 普通靜態(tài)常量不能提供檢查
枚舉:
public class Demo{
enum Status{
IDLE,PROCESSING,DONE,CANCELLED
}
Status status;
void setStatus(Status status){
this.status = status;
}
}
普通靜態(tài)常量:
public class Demo{
public static final int IDLE = 0;
public static final int CANCELLED = 1;
public int status;
//這里的參數(shù)不能提供檢查,可以傳入任意int
public setStatus(int status) {
this.status = status;
}
}
枚舉型注解:
public static class Status {
public static final int IDLE = 0;
public static final int CANCELLED = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef({Status.IDLE, Status.CANCELLED})
public @interface StatusTypeDef {
}
public int status;
@StatusTypeDef
public int getStatus() {
return status;
}
public void setStatus(@StatusTypeDef int status) {
this.status = status;
}
}
其他利用注解增強(qiáng)代碼的靜態(tài)檢查
dependencies { compile 'com.android.support:support-annotations:23.3.0'}
official Android annotations guide
annotations | description |
---|---|
@Nullable | Can be null. |
@NonNull | Cannot be null. |
@StringRes | References a R.string resource. |
@DrawableRes | References a Drawable resource. |
@ColorRes | References a Color resource. |
@Interpolator | Res References a Interpolator resource. |
@AnyRes | References any type of R. resource. |
@UiThread | Should only be called on the UI thread |
例子:
- public View onCreateView(@NonNull Context context);
- public abstract void setTitle(@StringRes int resId);
- public void setAlpha(@IntRange(from=0,to=255) int alpha) {}
- public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha){}