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.
0
3 comments

Hi,

Please always provide the full context. What class is not found? Always provide full stacktrace.

0

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.

package com.foo;

public class Test {
	private String a1;
	private String a2;
	//Getters & Setters
}

 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. 

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 try to call Class.forName("com.foo.Test")   in createObject method it throws ClassNotFoundException. 

Hope, now it is clear.

StackTrace

 

java.lang.ClassNotFoundException: Main PluginClassLoader(plugin=PluginDescriptor(name=ClassTo, id=com.foo.Main, descriptorPath=plugin.xml, path=~/Documents/jan/Code/Java/ClassTo/build/idea-sandbox/plugins/ClassToJson, version=1.0-SNAPSHOT, package=null, isBundled=false), packagePrefix=null, instanceId=73, state=active)
	at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:214)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
	at java.base/java.lang.Class.forName0(Native Method)
	at java.base/java.lang.Class.forName(Class.java:375)
	at GenerateAction.createObject(GenerateAction.kt:27)
	at GenerateAction.actionPerformed(GenerateAction.kt:17)
	at com.intellij.openapi.actionSystem.ex.ActionUtil.doPerformActionOrShowPopup(ActionUtil.java:315)
	at com.intellij.openapi.actionSystem.ex.ActionUtil.lambda$performActionDumbAwareWithCallbacks$4(ActionUtil.java:294)
	at com.intellij.openapi.actionSystem.ex.ActionUtil.performDumbAwareWithCallbacks(ActionUtil.java:337)
	at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks(ActionUtil.java:294)
	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$performAction$4(ActionMenuItem.java:293)
	at com.intellij.openapi.wm.impl.FocusManagerImpl.runOnOwnContext(FocusManagerImpl.java:227)
	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.performAction(ActionMenuItem.java:286)
	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$new$0(ActionMenuItem.java:67)
	at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$fireActionPerformed$3(ActionMenuItem.java:109)
	at com.intellij.openapi.application.TransactionGuardImpl.performActivity(TransactionGuardImpl.java:105)
	at com.intellij.openapi.application.TransactionGuardImpl.performUserActivity(TransactionGuardImpl.java:94)
	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.fireActionPerformed(ActionMenuItem.java:109)
	at com.intellij.ui.plaf.beg.BegMenuItemUI.doClick(BegMenuItemUI.java:546)
	at com.intellij.ui.plaf.beg.BegMenuItemUI$MyMouseInputHandler.mouseReleased(BegMenuItemUI.java:578)
	at java.desktop/java.awt.Component.processMouseEvent(Component.java:6648)
	at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3392)
	at java.desktop/java.awt.Component.processEvent(Component.java:6413)
	at java.desktop/java.awt.Container.processEvent(Container.java:2266)
	at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5022)
	at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
	at java.desktop/java.awt.Component.dispatchEvent(Component.java:4854)
	at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
	at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
	at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
	at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
	at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2802)
	at java.desktop/java.awt.Component.dispatchEvent(Component.java:4854)
	at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:781)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:730)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:724)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
	at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:754)
	at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:752)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
	at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:751)
	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:918)
	at com.intellij.ide.IdeEventQueue.dispatchMouseEvent(IdeEventQueue.java:840)
	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:763)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$6(IdeEventQueue.java:450)
	at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:791)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$7(IdeEventQueue.java:449)
	at com.intellij.openapi.application.TransactionGuardImpl.performActivity(TransactionGuardImpl.java:113)
	at com.intellij.ide.IdeEventQueue.performActivity(IdeEventQueue.java:624)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:447)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:881)
	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:493)
	at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:207)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:92)
0

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.

0

Please sign in to leave a comment.