I have a project created by others that includes thousands of class files and has the package names explicitly typed out for every reference to any of their classes. It looks like the code was reverse engineered. Is there a good tool for Java that refactors the code so that the explicitly typed package prefixes are removed from class references and moved into import statements.
Thank you in advance.
EDIT:
I think an example will help. I want to have the imports at the top, and I don't care how many imports there are.
javax.swing.JButton button1 = new javax.swing.JButton();
Imagine the code above but absolutely everywhere in thousands upon thousands of lines of code amongst thousands of class files. I would like to be able to remove all of the prefixes and just have a nice import javax.swing.JButton; at the top of each class file.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java. lang package and (2) the current package (the package for the current file).
Import statements have to be the first code in a Java source file. An import statement tells Java which class you mean when you use a short name (like List ). It tells Java where to find the definition of that class. You can import just the classes you need from a package as shown below.
Util package in Java is a built-in package that contains several pre-written utility classes and interfaces. The import java. util. *; statement can be used to load the contents of the Util package in a Java program. It consists of components such as data structures, exceptions, enumerations, utility classes, etc.
The import statement is optional, and we can use the fully-qualified name of the class to refer to a class or package in the program. This method tells the compiler that the class is defined under a particular package, and we want to use that class or classes in our program.
I don't know a tool for this use case, but I had to do something similar a few month ago.
Write a script or do a search replace with regex to get rid of the explicitly typed package prefixes.
Than let eclipse do the rest using "organize imports". Ctrl-1
Hint: to avoid ambiguities, setup the classpath with no more than the required libs. For sround about 800 classes I was done in 2 hours.
EDIT: You should know that in Prefeneces/Java/Editor/Save Actions, Organize imports can be configured as save action.
For a single type, eclipse offers the 'Add import' action (Shift+Ctrl+M). It does exactly what you want - with the big, big limitation: you have to place the cursor on a type and it will only affect that 'selected' occurrence.
But maybe this action can be used in a scripted/global method. A JDT plugin could crawl through the AST and call this action on every type it finds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With