How to get KtClass from PsiElement or VirtualFile?

795 Views Asked by At

I want to make an plugin that generate some template code for some specific kotlin files. Now I need to get KtClass from PsiElement or VirtualFile. I tried some code as below, but it's not working.

val psiFile = e.getData(CommonDataKeys.PSI_FILE)
        psiFile ?: return
        val editor = e.getData(CommonDataKeys.EDITOR)
        editor ?: return
        println(psiFile.name)
        val pe = psiFile.findElementAt(editor.caretModel.offset)
        if (pe != null) {
            println(pe.text)
        } else {
            println("PE is null")
        }
        val kt = PsiTreeUtil.getParentOfType(pe, KtClass::class.java)
        kt?.run {
            println(this.text)
        }

PS: I found that there are 2 PsiTreeUtils, one from org.jetbrains.kotlin.com.intellij.psi.util package, and another from com.intellij.psi.util, I don't know which one should I use

1

There are 1 best solutions below

0
On

A PsiFile might contain zero or more KtClasss. You can get them all by doing this:

val classes = psiFile.getChildrenOfType<KtClass>().asList()