Android Studio ParcelCreator Lint实现源码解析

效果图

源码ParcelDetector.java

ParcelDetector实现了JavaPsiScanner java文件检测接口

核心代码

  
    @Nullable
    @Override
    public List applicableSuperClasses() {
        return Collections.singletonList(CLASS_PARCELABLE);
    }

    @Override
    public void checkClass(@NonNull JavaContext context, @NonNull PsiClass declaration) {
        if (declaration instanceof PsiAnonymousClass) {
            // Anonymous classes aren't parcelable
            return;
        }

        // Only applies to concrete classes
        if (declaration.isInterface()) {
            return;
        }
        if (declaration.hasModifierProperty(PsiModifier.ABSTRACT)) {
            return;
        }

        // Parceling spans is handled in TextUtils#CHAR_SEQUENCE_CREATOR
        if (context.getEvaluator().implementsInterface(declaration,
                "android.text.ParcelableSpan", false)) {
            return;
        }

        PsiField field = declaration.findFieldByName("CREATOR", true);
        if (field == null) {
            Location location = context.getNameLocation(declaration);
            context.report(ISSUE, declaration, location,
                    "This class implements `Parcelable` but does not "
                            + "provide a `CREATOR` field");
        }
    }

实现函数解析

  • applicableSuperClasses

这个方法用来返回你感兴趣的那些父类,所以这里android.os.Parcelable(SdkConstants.CLASS_PARCELABLE ),此方法配合以下方法使用

  • checkClass(JavaContext context,PsiClass declaration)

检测到父类为以上指定的类是会触发此方法

  • 判断是不是注解类 declaration instanceof PsiAnonymousClass

  • 判断是不是接口declaration.isInterface()

  • 判断是不是抽象类declaration.hasModifierProperty(PsiModifier.ABSTRACT)

  • 判断PsiClass是否实现指定接口
    JavaEvaluator.implementsInterface(PsiClass cls,String interfaceName,boolean strict)

    • interfaceName 接口名称如:android.text.ParcelableSpan
    • strict 不清楚(大多数代码都是false)
  • 获取成员变量PsiClass.findFieldByName(String name, boolean checkBases)

    • name 变量名
    • 是否校验父类

你可能感兴趣的:(Android Studio ParcelCreator Lint实现源码解析)