Fail to create object using Intellij idea plugin API
Answered
I'm creating a IntelliJ plugin & Want to acheive following.
While doing a code in IntelliJ, if user right clicks in any Java file, I want to create a object of that class (Provided it is a valid class as per java specs).
Below is the code I tried to do the same.
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.util.PsiTreeUtil
class GenerateAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
e.getData(CommonDataKeys.EDITOR)?.let {
val clazz = getClass(it, e.project)
if (clazz != null) {
e.project?.let { createObject(clazz) }
}
};
}
private fun createObject(psiClass: PsiClass){
Class.forName(psiClass.qualifiedName);
}
fun getClass(editor: Editor, project: Project?): PsiClass? {
val psiFile = PsiDocumentManager.getInstance(project!!).getPsiFile(editor.getDocument())
val elementAtCaret = psiFile!!.findElementAt(editor.getCaretModel().getOffset())
return PsiTreeUtil.getParentOfType(
elementAtCaret,
PsiClass::class.java
)
}
}
When I tried to create a object it throws ClassNotFoundException. I tried multiple things including UrlClassLoader but no success.
Please sign in to leave a comment.
Hi,
Please always provide the full context. What class is not found? Always provide full stacktrace.
I've created a IntelliJ Plugin & I'm debugging the same.
While running/debugging IntelliJ plugin it open new IntelliJ window to debug/run your plugin functionality. So In that opened IntelliJ window, I created a Java Project and created a one class named as “Test ”under the package “com.foo”. Complete code is below.
I've created one action in plugin called “Create Object” which is handled in “GenerateAction” class. I want to create a object of this “Test” class when I right click and select Create Object menu. For creating object I've tried to use below code.
When I try to call
Class.forName("com.foo.Test")
increateObject
method it throws ClassNotFoundException.Hope, now it is clear.
StackTrace
Hi,
Thank you for clarifying. It is clear now.
You cannot load a project class as it is not compiled and is not available in the classpath of the IDE/plugin. In order to do it, you would need to compile the class/project and load it with a dedicated classloader.
See https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000615544-Intellij-Plugin-Load-class-object-from-source-project for a similar discussion.
I suggest sharing your actual use case because maybe you are trying to do something that is possible in a much easier way (e.g., inspect class fields, methods, etc.), without having to load the class and creating an object.