javaandroid-studioclassorganizationcode-organization

How to automatically structure java class source code?


I am looking for a way to quickly organize source code within java classes, preferably have the different sections such as fields, methods, etc. in alphabetical order and within their own section. I have googled around and can't find any tool that does anything close to this. Am I the only one who would like something like this?

I am using Android Studio.

Here is an example of what I mean by "organize source code".

Going from this:

class ExampleClass{
    
    private String text;
    private boolean flag;
    
    public void method{
        int i = 2;
    }
    
    public int number;
    
    
    
    private boolean getFlag(){
        return this.flag;
    }
    
    private ExampleInnerInterface interface;
    
    interface ExampleInnerInterface{
        void fire();
    }
    
    private void setFlag(boolean flag){
        this.flag = flag;
    }
}

To this:

class ExampleClass {

  //  Fields
  public int number;

  private boolean flag;
  private ExampleInnerInterface interface;
  private String text;

  //  Getters
  private boolean getFlag() {
    return this.flag;
  }

  //  Setters
  private void setFlag(boolean flag) {
    this.flag = flag;
  }

  //  Methods
  public void method {
    int i = 2;
  }

  //  Inner classes
  interface ExampleInnerInterface {
    void fire();
  }
}

This type of organization makes it a lot easier for me to manage my code. I know that you can just search for what you want, so finding what you need isn't hard at all. I want this to be clean for when I do handovers, which would cause a scenario where the person would need to know what is searchable before they can search for it.

Any help would appreciated!


Solution

  • In AndroidStudio (and all modern variants of IntelliJ) go the Code menu -> Reformat File... and in the dialog make sure you check the options Optimize Imports, Rearrange Code and Code Cleanup. It does not sort methods alphabetically, but at least it

    The behavior can also be influenced by the languages code style in the IDEs perferences (at least the pure formatting stuff, like where to put spaces, parentheses and so on).