How to auto align “{” braces of statement blocks for Java in Eclipse

Eclipse 3.4 for Java EE came with a default code style for Java where the braces of statement blocks are not aligned. It looks like this: 

public class MyClass
{
    private String myVar; 

    public MyClass() {
       myVar = "Some text here for now";
    }
}

Instead, some people prefer to align statement block braces because it’s easier to keep track of them that way. Aligned braces look like this:

public class MyClass
{
    private String myVar; 

    public MyIntStack()
    {
	 myVar = "Some text here for now";
    }
}

Here’s how to change this so that any auto-generated Eclipse code (like Source > Generate Getters and Setters) shows up with aligned braces.

Step 1. Go to Eclipse Preferences.

  • On OS X go to Eclipse > Preferences.
  • Click on arrow next to Java in the list on the left
  • In the expanded menu, click on arrow next to Code Style
  • Click on Formatter
  • Click the Edit… button ( In EasyEclipse 1.2, it’s the Show… button)

3

Step 2. Create a custom Profile.

  • Select the Braces tab
  • Change the “Profile name” to something unique
  • And now a somewhat tedious task: Select “Next line” for each of the elements under “Brace positions” (wouldn’t it be great if there was a “Change All” drop-down option? Mmmm, Usability?)

4

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s