How to find the class of a function call (KtNameReferenceExpression)

Answered

Hello,

I have a PsiElement of type KtCallExpression which I can use to get access to a KtNameReferenceExpression`. Is there an utility class in Intellij Idea Plugin SDK in order to give you the class where the function is declared?

Example:
Having the following code:

LayoutInflater.from(context).inflate(R.layout.my_layout)

How can I get the class name of the method inflate?

Thank you in advance.

2 comments
Comment actions Permalink

Hi! You can use something like this to get the class name

fun findContainingClassName(callExpression: KtCallExpression): String? {
val callableDescriptor = callExpression.resolveToCall()?.resultingDescriptor ?: return null
val classDescriptor = callableDescriptor.containingDeclaration as? ClassDescriptor ?: return null
return classDescriptor.name.asString() //or `classDescriptor.fqNameOrNull()?.asString()`
}

If you want to get KtClassOrObject, then you can use

val classDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(callExpression.project, classDescriptor) as? KtClassOrObject

or

val callableDeclaration = callExpression.mainReference.resolve() as? KtCallableDeclaration ?: return null
val classDeclaration = callableDeclaration.containingClassOrObject
0
Comment actions Permalink

Thank you a lot Dmitry, I still didn't manage to find a solution, so that its helpful. I will leave the feedback as soon as I can test the suggestion. Kind regards.

0

Please sign in to leave a comment.