3

I want to create a big Java object with 20 fileds, most of IDE's provide a generate function, wich allows me to generate getters and setters for all the fiels 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 ?

Will
  • 2,057
  • 1
  • 22
  • 34

3 Answers3

6

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)

Vitaliy Moskalyuk
  • 2,463
  • 13
  • 15
6

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());
    }
}
Amber Kulkarni
  • 424
  • 8
  • 17
  • 1
    Use *lombok* with care! It changes the bytecode bypassing the JDKs compiler and you have to expect incompatibilities with future java versions. – Timothy Truckle Jun 06 '17 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.

assylias
  • 321,522
  • 82
  • 660
  • 783