Fireburn Fireburn - 3 months ago 6
Java Question

Add Java import statements automatically via script

Eclipse Java IDE has a shortcut Ctrl+Shift+O to automatically add unused imports. Where I can find script (bash, python or something other that can be executed via shell) to do this IDE-agnostically, for example, in text editor that can use scripted external tools like gedit?

Answer

Make a script that parses in the classes inside the .jar files located in your Java installation, taking in account the directory name and class name to determine the fully qualified name.

For instance, java.lang.String class is located in <jre installation>\lib\rt.jar.

If you reference multiple classes called String, get all fully qualified names with class name String, and simply handle some shell input to determine which package should be used. If there is only one with that name, import it if it hasn't been already.

Should be simple enough in any language that can handle iterating files in JARs.