How to add import statement to the class programatically

I want to add the import statements to a class programtically, how can i do this. In eclispe  there is something like compUnit.createImport(), do we have something similar in intellij.

Comment actions Permalink

Usually you don't need to add imports manually, you can use qualified class names in added methods/fields instead and then call
JavaCodeStyleManager#shortenClassReferences to let IDEA add required imports automatically in sorted order accordingly to the project code style

Nikolay Chashnikov
"Develop with pleasure!"

Comment actions Permalink

Thanks for this, Nikolay. I have been picking at this issue for several days now. I finally decided to see if there was a plugin development forum and search for my problem and found your post immediately.

    private void createImports(AnActionEvent actionEvent) {
        final Project currentProject = getEventProject(actionEvent);
        final PsiFile currentFile = actionEvent.getData(LangDataKeys.PSI_FILE);
        if (currentProject != null && currentFile != null) {
            // Get an instance of this project's coding-style manager
                    // Tell it to shorten all class references accordingly


Please sign in to leave a comment.