Handy Tool for Code Cleanup: Automated Class Element Reordering
By Geertjan-Oracle on Dec 11, 2012
You're working on an application and this thought occurs to you: "Wouldn't it be cool if I could define rules specifying that all static members, initializers, and fields should always be at the top of the class? And then, whenever I wanted to, I'd start off a process that would actually do the reordering for me, moving class elements around, based on the rules I had defined, automatically, across one or more classes or packages or even complete code bases, all at the same time?"
Well, here you go:
That's where you can set rules for the ordering of your class members. A new hint (i.e., new in NetBeans IDE 7.3), which you need to enable yourself because by default it is disabled, let's the IDE show a hint in the Java Editor whenever there's code that isn't ordered according to the rules you defined:
The first element in a file that the Java Editor identifies as not matching your rules gets a lightbulb hint shown in the left sidebar:
Then, when you click the lightbulb, automatically the file is reordered according to your defined rules.
However, it's not much fun going through each file individually to fix class elements as shown above. For that reason, you can go to "Refactor | Inspect and Transform". There, in the "Inspect and Transform" dialog, you can choose the hint shown above and then specify that you'd like it to be applied to a scope of your choice, which could be a file, a package, a project, combinations of these, or all of the open projects, as shown below:
Then, when Inspect is clicked, the Refactoring window shows all the members that are ordered in ways that don't conform to your rules:
Click "Do Refactoring" above and, in one fell swoop, all the class elements within the selected scope are ordered according to your rules.