How to stop Eclipse reformating your Java enumerations & comments

Eclipse is a wonderful IDE for the Java language and I’ve used it daily for at least the past 4 years but it does have some 'issues'. One is regarding it’s code formatting (or reformatting) support, normally it does a great job of putting stuff in the right place but there are occasions where it just fails to get it right.

When I write enums I like to have each item on it's own row, I find it's easier to read and amend in the future:

public enum Family {
But Eclipse has other ideas and formats it so that it looks like this:
public enum Family {
A way to get around this (and any other times where you have a few lines of code that you don't want collapsing into one is to add the double-slash style code comments to the end of each line:
public enum Family {
    MOTHER, //
    FATHER, //
    DAUGHTER, //
Block comments

I recently wanted to have a decent sized chunk of XML stored within Java's block comments (/* ... */) so that I could refer to it as I coded a mapping class. Everytime I saved the class Eclipse reformatted my XML so that it looked like someone had been sick on the page.

After a little digging I found this gem buried in the original coding conventions document from Sun back in 1997:
Block comments can start with /*-, which is recognized by indent(1) as the beginning of a block comment that should not reformatted.
    Taken from section 5.1.1 of Java Code Conventions

Now I'm pretty damn sure that Eclipse doesn't use indent for it's layout but I tried it anyway and it works a treat! Simply add the minus sign to the start of the block comment section and it will leave the whole block comment alone:
            XML which we don't want


David Lund said...

You can also use:

/* @formatter:off */
// Do what you like in here, eclipse wont format it
/* @formatter:on */

That will

Anonymous said...

Or you could use the Formatter option "Never join lines"