【问题标题】:Need to check sub class (of Class type) if it inherits from super class, using custom Detector via method visitCallExpression(UCallExpression)需要检查子类(类类型)是否继承自超类,通过方法 visitCallExpression(UCallExpression) 使用自定义检测器
【发布时间】:2021-11-09 15:45:02
【问题描述】:

我创建了自己的 lint Detector.visitCallExpression(UCallExpression),我需要找到一种方法来检查传递给方法调用的 MyClass 类参数是否是 MyParent 类的子类?

//Example having this below code somewhere to be Lint scanned.
someObject.method(MyClass.class)

如何确定 MyClass.class 继承自 MyParent 类?

//Using the IntelliJ InheritanceUtil utility class
//Converts argument of MyClass.class -> psiClass
InheritanceUtil.isInheritor(psiClass, "com.somePackage.MyParent")

我从 MyClass.class 参数中得到的 PsiClass 被解析为基础 java.lang.Class 对象,所以 InheritanceUtil 检查总是返回 false~

【问题讨论】:

    标签: intellij-plugin android-lint


    【解决方案1】:

    反正我找到了解决办法

    /**
     * Detects if a Class<?> => PsiClass:Class<?> is a subclass of a PsiClass(?)
     *
     * @param type The PsiType object that is a PsiClass of the class to be checked for subclass
     * @param compareToParentCanonicalClass The Class canonical name to be compared as a super/parent class
     *
     * @return true if the PsiType is a subclass of compareToParentCanonicalClass, false otherwise
     */
    open fun isPsiTypeSubClassOfParentClassType(type: PsiType, compareToParentCanonicalClass: String): Boolean {
        println("superClass checking:$type")
        var psiClss = PsiTypesUtil.getPsiClass(type)
        val pct = type as PsiClassType
        val psiTypes: List<PsiType> = ArrayList<PsiType>(pct.resolveGenerics().substitutor.substitutionMap.values)
        for (i in psiTypes.indices) {
            println("canonical:"+ psiTypes[i].canonicalText)
            var psiClass = psiClss?.let { JavaPsiFacade.getInstance(it.project).findClass(psiTypes[i].canonicalText, psiClss.resolveScope) }
            return InheritanceUtil.isInheritor(psiClass, compareToParentCanonicalClass)
        }
        return false;
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2023-03-29
    • 2012-10-09
    • 1970-01-01
    • 2011-03-06
    • 2020-08-27
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多