【问题标题】:Cannot Cast PsiElement to KtClass - Intellij无法将 PsiElement 转换为 KtClass - Intellij
【发布时间】:2020-04-03 22:23:38
【问题描述】:

我正在学习为 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$1.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$2(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
}

这是我的毕业论文:

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'
}

【问题讨论】:

  • 看起来有来自两个不同类加载器的 2 个 KtClass 类。第一个来自 intellij 插件,第二个来自dependencies。您能否尝试将implementation 更改为compileOnlykotlin-stdlib-jdk8
  • @Feedforward 我将依赖项更改为如下所示。 dependencies { compileOnly "org.jetbrains.kotlin:kotlin-stdlib-jdk8" implementation "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61" } 但我仍然遇到同样的错误

标签: intellij-idea kotlin jetbrains-ide intellij-plugin


【解决方案1】:

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

  1. 使用“导入 org.jetbrains.kotlin.com.intellij.psi.PsiElement” 来自 Kotlin Plugin 而不是“com.intellij.psi.PsiElement” 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-09
    • 2015-04-11
    • 2017-10-29
    • 1970-01-01
    • 2015-09-04
    • 2016-05-26
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多