Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate setters which return Object(self) in Android Studio or Intellij-Idea

Im looking to easy way to set many parameters to object and return object itself. So I can set any object. something like:

public class Foo {

    private int mValue1;
    private String mValue2;
    private boolean mValue3;
    private long mValue4;

    public Foo() {
    }

    public Foo setValue1(int value1) {
        mValue1 = value1;
        return this;
    }

    public Foo setValue2(String value2) {
        mValue2 = value2;
        return this;
    }

    public Foo setValue3(boolean value3) {
        mValue3 = value3;
        return this;
    }

    public Foo setValue4(long value4) {
        mValue4 = value4;
        return this;
    }
}

I am looking for an auto-generate tool which helps me to achieve that.

Having them(members) in constructor enforcing me to set null for all members. Also having over-loading constructors are headache when update members.

like image 747
Maher Abuthraa Avatar asked Jan 13 '17 18:01

Maher Abuthraa


1 Answers

I think I found the answer .. There is a shipped template called Builder with Android Studio (Intellij-Idea) does that job smoothly.

  1. Press when you want to generate setters inside class
  2. +N on OSX or ALT+Insert on Windows/Linux ( credit to Shashanth ). You can also run generate via menu Code => Generate
  3. Click on Setters
  4. Switch to Builder template from Template menu
  5. Select members to be generated
  6. OK

Even more you can customise the setter template 🙂

Good luck,'.

generate setter which returns self (this)

like image 149
Maher Abuthraa Avatar answered Oct 22 '22 00:10

Maher Abuthraa