Android 包android.support.annotation包提供了诸如 @IntDef 和 @StringDef 等注解,可以让AS, Lint 提供静态代码检查功能
用注解型枚举代替普通静态常量和枚举
原因:
- 枚举销毁的内存是普通静态常量的两倍
- 普通静态常量不能提供检查
枚举:
public class Demo{
enum Status{
IDLE,PROCESSING,DONE,CANCELLED
}
Status status;
void setStatus(Status status){
this.status = status;
}
}
普通静态常量:
public class Demo{
public static final int IDLE = 0;
public static final int CANCELLED = 1;
public int status;
//这里的参数不能提供检查,可以传入任意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;
}
}
其他利用注解增强代码的静态检查
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){}
网友评论