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.

2 comments

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
settings.

--
Nikolay Chashnikov
JetBrains
http://www.jetbrains.com
"Develop with pleasure!"

0

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
            JavaCodeStyleManager.getInstance(currentProject)
                    // Tell it to shorten all class references accordingly
                    .shortenClassReferences(currentFile);
        }
    }

0

Please sign in to leave a comment.