如何将PsiElement转换为PsiClass

时间:2015-11-19 02:16:48

标签: intellij-idea intellij-plugin

PsiElement referenceAt = psiFile.findElementAt(editor.getCaretModel().getOffset());


PsiClass parentOfType = PsiTreeUtil.getParentOfType(referenceAt, PsiClass.class);

WriteCommandAction.runWriteCommandAction(project, () -> {
if (referenceAt instanceof PsiClass){
    editor.getDocument().insertString(editor.getCaretModel().getOffset(), "isClass");
} else if (referenceAt instanceof PsiVariable){
    editor.getDocument().insertString(editor.getCaretModel().getOffset(), "isVariable");
}


}

现在我可以提取插入符号所在元素的名称。我的目标是找出Psi​​Element是否为Class。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

如果插入符号在引用上,而不在实际声明中,则需要解析该引用以获取PsiClass

PsiReference reference = referenceAt.getReference();
if (reference != null) {
    PsiElement target = reference.resolve();
    if (target instanceof PsiClass) {
        // do your things here
    }
}