0

I have created my own lint Detector.visitCallExpression(UCallExpression) and I need to find a way to check if a MyClass class parameter passed into a method call is a child of MyParent class?

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

How can I determine MyClass.class inherits from MyParent class?

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

The PsiClass I get from the MyClass.class parameter, is resolved to the base java.lang.Class object, so the InheritanceUtil check always return false~

Cozytrony
  • 1
  • 1

1 Answers1

0

Anyway i found the solution

    /**
     * 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;
    }
Mohamed Ibrahim
  • 3,714
  • 2
  • 22
  • 44
Cozytrony
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 15 '21 at 14:41