无法将 PsiElement 转换为 KtClass - Intellij

Cannot Cast PsiElement to KtClass - Intellij

我正在学习为 IntelliJ 创建插件,但我被困在 PsiElement 上。我无法将 PsiElement 转换为 KtClass,即使它也是一个 KtClass。

这是错误日志

java.lang.ClassCastException: org.jetbrains.kotlin.psi.KtClass cannot be cast to org.jetbrains.kotlin.psi.KtClass
    at action.MyAction.getPsiClassFromEvent(MyAction.kt:32)
    at action.MyAction.actionPerformed(MyAction.kt:21)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.run(ActionUtil.java:261)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:278)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks(ActionUtil.java:252)
    at com.intellij.ui.popup.ActionPopupStep.performAction(ActionPopupStep.java:200)
    at com.intellij.ui.popup.ActionPopupStep.performAction(ActionPopupStep.java:190)
    at com.intellij.ui.popup.ActionPopupStep.lambda$onChosen(ActionPopupStep.java:184)
    ...
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

这是我的函数

private fun getPsiClassFromEvent(e: AnActionEvent): KtClass? {
    val psiElement = e.getData(
        LangDataKeys.PSI_ELEMENT
    ) ?: return null

    return psiElement as KtClass
}

这是我的 gradle:

plugins {
    id 'org.jetbrains.intellij' version '0.4.15'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
}

group 'intellijtemplate.djaka.id'
version '1.0-SNAPSHOT'

apply plugin: 'org.jetbrains.intellij'
apply plugin: 'kotlin'

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"
}

intellij {
    version '2019.1.4'
    plugins 'org.jetbrains.kotlin:1.3.11-release-IJ2018.3-1'
}

我也找到了问题,感谢 Yann Cebron。结果:

  1. 使用"import org.jetbrains.kotlin.com.intellij.psi.PsiElement" 来自 Kotlin Plugin 而不是 "com.intellij.psi.PsiElement" in KtClassHelper
  2. 在build.gradle中, "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61" 被收录到 项目而不是 buildscript 类路径

完整答案在这里:https://intellij-support.jetbrains.com/hc/en-us/community/posts/360006794080-Cannot-Cast-PsiElement-to-KtClass