Android--提升代码检查的注解

摘译

原文地址:https://developer.android.google.cn/studio/write/annotations

需要 android.support.annotation, 对应com.android.support:support-annotations:$version (应该都是集成了的,appcompat包含这个库)
如果在lib中使用,会被打包进AAR, 以xml的形式存在于annotations.zip文件

注解列表:https://developer.android.google.cn/reference/android/support/annotation/package-summary
特别看到:PluralsRes、GuardedBy、FractionRes

注解的相关检查通过lint处理。lint不强制nullness标签,只是AS会处理;并且lint的警告并不影响实际编译

nullness注解


@Nullable,@NonNull(注意是Android的而不是IntelliJ的)
kotlin中,声明非空的变量无需添加,因为编译后自动添加
可以使用功能: Analyze > Infer Nullity 检测是否需要添加

资源注解


BoolRes

AARRGGBB 和 RRGGBB 不属于@ColorRes, 需要使用@ColorIntger@ColorLong

线程注解


@MainThread@UiThread,在构建工具中是可互换的。但是两者还是有些不同,参看:https://stackoverflow.com/questions/40784584/difference-between-the-main-thread-and-ui-thread/40795895#40795895
因此,完美的写法还是对 关联app生命周期的方法标注Main, 对 关联app View结构的方法标注Ui

值约束 注解


*Range,@Size

setAlpha(@FloatRange(from=0.0, to=1.0) float alpha)

void getLocation(View button, @Size(min=1) int[] location) {
    button.getLocationOnScreen(location);
}

权限注解


这一章会写到权限介绍部分中
https://developer.android.google.cn/studio/write/annotations#permissions

返回值检查 注解


@CheckResult(suggest="#enforcePermission(String,int,int,String)")
public abstract int checkPermission(@NonNull String permission, int pid, int uid);

类型定义 注解


//如果TYPE_ONE, TYPE_TWO 可以组合(|,,&, ^ 等),flag = true  
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = false, value = {TYPE_ONE, TYPE_TWO})
public @interface Type {}

keep 注解


使用@Keep注解之后,即使被注解的类或方法没有被用到,也会被打包

如果是通过反射获取注解,则在proguard文件中使用 -if 条件声明(没看到过这种用法,文档也没示例,就提了Dagger和Butterknife,应该是过去式了)

可见性 注解


包括:方法、类、域名、包 ; 和API约束 的第三种效果一样

//otherwise是指  除了myMethod附属的其他类
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
void myMethod() { ... }

API约束 注解


//限定子类访问
@RestrictTo(RestrictTo.Scope.SUBCLASSES)  
//库范围访问
@RestrictTo(RestrictTo.Scope.GROUP_ID)
//测试代码访问
@RestrictTo(RestrictTo.Scope.TESTS)

猜你喜欢

转载自blog.csdn.net/u013867301/article/details/84539423