Nullness注解
名稱(chēng) | 參數(shù) | Target | 含義 |
---|---|---|---|
@Nullable | - | PARAMETER | 可以為null |
@NonNull | - | PARAMETER | 不可為null |
資源注解
資源注解的Target都是PARAMETER
名稱(chēng) | 參數(shù) | 含義 |
---|---|---|
@AniamtorRes | - | R.ainimaor |
@AnimRes | - | R.ainim |
@AnyRes | - | 任意資源類(lèi)型 |
@AttrRes | - | R.arry |
@BoolRes | - | 布爾型 |
@ColorRes | - | R.color |
@DrawableRes | - | R.drawable |
@Fraction | - | 多用于Animation XML中,50%p |
@IdRes | - | R.id |
@InterpolatorRes | - | R.interpolator |
@LayoutRes | - | R.layout |
@MenuRes | - | R.menu |
@PluralsRes | - | 表示復(fù)數(shù)類(lèi)型字符串 |
@RawRes | - | R.raw |
@StringRes | - | R.string |
@StyleableRes | - | R.styleable |
@StyleRes | - | R.style |
@TransitionRes | - | 標(biāo)記整型值是transition類(lèi)型的 |
@XmlRes | - | R.xml |
類(lèi)型定義注解@IntDef
使用情景:
聲明的一組int常量來(lái)表示類(lèi)型,如果某方法只接收這幾種常量,可以使用@IntDef; 如果某方法只要求返回這幾種常量,可以使用@IntDef。
-
example1:
注解定義:
@Retention(SOURCE)
@IntDef({ORIGINAL, PORTRAIT})//常量可聲明在任意位置
public @interface MyType {
}
使用:
public void setType(@MyType int type) {
}
這如下方式使用時(shí),則編譯器會(huì)報(bào)錯(cuò)
setType(8);
- example2
@IntDef(flag = true, value = {ORIGINAL, PORTRAIT}) //常量可聲明在任意位置
public @interface MyType {
}
使用:
@MyType
public int getType() {
return 99; // 返回值與常量不相等,則報(bào)錯(cuò)
}
線(xiàn)程注解
@Target({METHOD,CONSTRUCTOR,TYPE})
- @UiThread @MainThread
- @WorkerThread
- @BinderThread
RGB 顏色值注解
@Target({PARAMETER,METHOD,LOCAL_VARIABLE,FIELD}
- @ColorInt
值范圍注解
@Target({METHOD,PARAMETER,FIELD,LOCAL_VARIABLE})
-
@Size
源碼:
@Retention(CLASS)
@Target({PARAMETER,LOCAL_VARIABLE,METHOD,FIELD,ANNOTATION_TYPE})
public @interface Size {
/** An exact size (or -1 if not specified) */
long value() default -1;
/** A minimum size, inclusive */
long min() default Long.MIN_VALUE;
/** A maximum size, inclusive */
long max() default Long.MAX_VALUE;
/** The size must be a multiple of this factor */
long multiple() default 1;
}
對(duì)于數(shù)組、集合字符串之類(lèi)的參數(shù),可以用@Size來(lái)表示這些參數(shù)的大小
* @Size(min=1), 表示集不為空
* @Size(max=23),表示字符串最大字符個(gè)數(shù)是23
* @Size(2), 表示元素個(gè)數(shù)是2
* @Size(multiple=2), 數(shù)組大小是2的倍數(shù)
- @IntRange
@IntRange(from=2,to=10) - @FloatRange
@FloatRange(from=0.0,to=1.0)
權(quán)限注解
@Target({ANNOTATION_TYPE,METHOD,CONSTRUCTOR,FIELD})
- @RequiresPermission(permision)<Br/>
@RequiresPermission(allOf={permision1,perminsion2})<Br/>
@RequiresPermission(anyOf={permision1,perminsion2})
重寫(xiě)方法注解
@Target({METHOD})
- @CallSuper 子類(lèi)重寫(xiě)某個(gè)方法時(shí),要求調(diào)用super,可以使用該注解
@CheckResult
提醒方法的調(diào)用者對(duì)方法的返回值進(jìn)行檢查
@VisibilityForTesting
@Keep
標(biāo)記此類(lèi)或方法不會(huì)被混淆