How can I get the full name of KtNameReferenceExpression represent reference?



I am developing a codegen IDEA Plugin. I have stuck in getting the full name of KtNameReferenceExpression represent reference for a long time.

For Example:


data class TestBean(


    val tag: String = ""

): IConfig


The part where font is bold is stored as KtNameReferenceExpression in Psi Tree.

Unfortunately, KtNameReferenceExpression seemingly only contains simple name info (in this case is "KEY_TAG" and "IConfig"), which is not I am seeking for ("com.example.config.KEY_TAG" and "com.example.config.IConfig")


I have try to traverse the KtFile and find any information about "KEY_TAG" or "IConfig", like trying to find all top-level KtDeclaration and trying to find all import list. But it so complex, and I think there is to do this.


Could you please help me to find out a better and correct way to obtain KtNameReferenceExpression full name? Thank you! :)

Comment actions Permalink

Resolve the PsiReference from it to obtain the declaration org.jetbrains.kotlin.idea.references.ReferenceUtilsKt#getMainReference(org.jetbrains.kotlin.psi.KtSimpleNameExpression)

Comment actions Permalink

Sorry for slow response and Thank you Yann. Your solution is work for me.

Before your answer, I do thousand of invesigation and find that I can get a KtExpression(KtNameReferenceExpression is also a KtExpression) by BindingContext.


val bindingContext = expression.analyze()
val sourceElement = bindingContext.get(BindingContext.REFERENCE_TARGET, expression)?.toSourceElement
as? KotlinSourceElement
val ktProperty = sourceElement?.psi as? KtProperty
val classId = ktProperty?.type()?.constructor?.declarationDescriptor?.classId
val fullName = "${classId?.packageFqName}.${classId?.relativeClassName}"


Is this whether the method to get the full name of the KtExpression type is recommended? Thank you!


Please sign in to leave a comment.