Kotlin PSI find class based on typeReference

Answered

I'd like to read the KtParameter type and find the KtClass corresponding to that.
 Eg: I'd like to find the KtClass for "Menuitem" 

data class Popup(
val menuitem: List<Menuitem>,
val age: Int,
val item: Menuitem,
val decima: Float,
val string: String,
)

This will help me in reading the entire parameter declaration hierarchy in any class.

4 comments
Comment actions Permalink

Hi! You can use something like

val parameter: KtParameter
val element = (parameter.typeReference?.typeElement as KtUserType)?.referenceExpression?.mainReference?.resolve()

to find corresponding PSI element

0
Comment actions Permalink

Thank you!
I tried this but I'm unable to resolve mainReference . 

0
Comment actions Permalink

Dmitrii Gridin I was able to resolve mainReference but for some reason Im getting this error for mainReference:

No element of given type found

0
Comment actions Permalink

Finally, I got this working. 

Steps:

1. Enable type resolution for psi. In my case, it was detekt type resolution: https://detekt.dev/docs/gettingstarted/type-resolution 

Once you enable that, you'll be able to execute the following line:

If you need the FQ Name of the class

val classFqNameAsString = (bindingContext.get(BindingContext.TYPE, parameter.typeReference) as KotlinType).unwrap()
.constructor.getClassFqNameUnsafe().asString()

if you need PsiClass

val classFqNameAsString = (bindingContext.get(BindingContext.TYPE, parameter.typeReference) as KotlinType).unwrap()
.constructor.getClassFqNameUnsafe().asString()
val psiClassTypeFound: PsiClass? = JavaPsiFacade.getInstance(parameter.project).findClass(classFqNameAsString,parameter.resolveScope)

Make sure bindingContext is not empty

0

Please sign in to leave a comment.