Adding @Generated to IntelliJ's Getter/Setters Generator

I use IntelliJ’s shortcut for generating getters and setters for my classes all the time. Since this code is generated, I like to mark it as such with an @Generated annotation.

Why you should care

  • code marked as generated won’t show up as unused and clutter your screen with warnings
  • you can add a rule to your code coverage tool to ignore generated code when it’s analyzing your code
  • it sends a clear message to whomever is looking at it that the code was generated

Step By Step

Start with a class that needs getters / setters

    public class MySimpleClass {
        private String name;
        private int number;
    }

Right click and select Generate…

Make sure you right click in the body of the class and not outside of it. If you click outside of the body of the class, you’ll only see the Generate / Copyright option.

Select Getters / Setters

generate-menu.png

Open the script editor for the Getter

The script to generate the getter or setter is actually quite large but you won’t be editing anything apart from inserting one line at the top. First, you should make a copy of the existing default script.

Copy the IntelliJ default

I like to name the changed default to Generated for the getter or GeneratedBuilder for the setter.

Add the annotation to the top

Insert the following line at the top of the script editor:

@javax.annotation.Generated("generated by IDE")

The script will add an import for Generated if necessary to avoid writing the fully qualified name when it executes.

Repeat for the Setter

Done

The next time you launch this dialog it’ll remember your settings and your getters and setters will have the annotation on them.

When you run these generators on the sample class above, you’ll get the following output:

import javax.annotation.Generated;

public class MySimpleClass {
    private String name;
    private int number;

    @Generated("generated by IDE")
    public String getName() {
        return name;
    }

    @Generated("generated by IDE")
    public MySimpleClass setName(String name) {
        this.name = name;
        return this;
    }

    @Generated("generated by IDE")
    public int getNumber() {
        return number;
    }

    @Generated("generated by IDE")
    public MySimpleClass setNumber(int number) {
        this.number = number;
        return this;
    }
}
 Date: June 16, 2016
 Tags: 

Previous
⏪ Spring, Swagger and Apache CXF

Next
Deploying to Veracode with Bamboo ⏩