2

I want use this Java code in order to create Java Object:

public class NotificationMessage implements Serializable {

    private static final long serialVersionUID = 985577913631100757L;

    private int id;
    private String uniqueid;
    private String status;
    private String type;
    private Map<String, String> map;
    private Date created_at;

    public NotificationMessage() {
    }

    public NotificationMessage(int id, String uniqueid, String status, String type, Map<String, String> map,
            Date created_at) {
        this.id = id;
        this.uniqueid = uniqueid;
        this.status = status;
        this.type = type;
        this.map = map;
        this.created_at = created_at;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
....
}

How I can use builder in order to minimize setters when I want to create Java object?

I want to set values like this:

NotificationMessage.builder().id(123).uniqueid(1234).status("active")
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

2 Answers2

2

You can use https://projectlombok.org/

@Entity
@Data
@Builder
@Getter
public class NotificationMessage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String uniqueid;
    private String status;
    private String type;
    private Map<String, String> map;
    private Date created_at;
}


NotificationMessage.builder().id(123).uniqueid(1234).status("active");

assertThat(NotificationMessage.getId()).isEqulTo(123));
Grzesiek
  • 715
  • 5
  • 24
0

In order to chain the method calls like that:

NotificationMessage.builder().id(123).uniqueid(1234).status("active")

You have to return the calling object (this) on each call:

public NotificationMessage id(int id) {
    this.id = id;
    return this;
}
jhamon
  • 3,603
  • 4
  • 26
  • 37
  • You are missing the crucial point: he doesn't understand what a Builder is, and what a (to be written method) `builder()` would return. – GhostCat Aug 13 '18 at 09:27
  • @jhamon this approach will make the java Object really fat. Is there other way to implement it? – Peter Penzov Aug 13 '18 at 09:28
  • You need to either write the builder manually or use a code-generating library like [Google AutoValue](https://github.com/google/auto/blob/master/value/userguide/index.md) or Project Lombok as explained in the other answer. – Mick Mnemonic Aug 13 '18 at 10:14