3

I want to create a big Java object with 20 fields, most IDEs provide a generate function, which allows me to generate getters and setters for all the fields of my object.

The thing is, I am a big fan of method chaining and I am using it on all my objects, but I have to add return this at the end of each setters, which is not very handy.

Is it possible to generate setters with a special plugin form an IDE?

6
  • 3
    How would you chain getters? Jun 6, 2017 at 11:56
  • My bad, edited.
    – Will
    Jun 6, 2017 at 12:01
  • @OliverCharlesworth You just blew my mind. But getters should probably not be chained (as they would serve no purpose otherwise).
    – Turtle
    Jun 6, 2017 at 12:01
  • FWIW, you should look into Immutables. Jun 6, 2017 at 12:04
  • @OliverCharlesworth while immutable DTOs/ValueObject are a very good idea fluent API on Builders is not that bad... ;o) Jun 6, 2017 at 12:11

3 Answers 3

8

It's possible in IntelliJ IDEA:

  1. call "Generate > Setter" menu
  2. select template "Builder".
  3. Select all fields you want to generate setter
  4. click 'Ok'.

Here is generated result (for 1 field):

public MyClass setParam(String param) {
        this.param = param;
        return this;
    }

It's also possible to create your own template there)

7

You can try lombok

lombok.accessors.chain = [true | false] (default: false)

If set to true, generated setters will return this (instead of void). An explicitly configured chain parameter of an @Accessors annotation takes precedence over this setting.

Is this what you want ? https://projectlombok.org/features/GetterSetter.html

@Accessors(chain = true)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE)

public class LombokTest {
    private String test;

    public static void main(String []args) {
        LombokTest a = new LombokTest();
        System.out.println(a.setTest("amber").getTest());
    }
}
1
  • 1
    Use lombok with care! It changes the bytecode bypassing the JDKs compiler and you have to expect incompatibilities with future java versions. Jun 6, 2017 at 12:13
3

It's generally called "fluent" setters. There is a plugin for Netbeans that does it automatically for you. I'm pretty sure you can find something equivalent in eclipse or IntelliJ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.