Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation for various constructors in Lombok?

Tags:

java

lombok

I have a class

public class Answer<T> {
    private T data;

    public Answer(T data) {
        this.data = data;
    }

    public Answer() {
    }

    public T getData() {
        return data;
    }

    public Answer<T> setData(T data) {
        this.data = data;
        return this;
    }
}

which I want to simplify with Lombok.

If I add annotation @AllArgsConstructor than I can't see default constructor.

@Data
@AllArgsConstructor
public class Answer<T> {
    private T data;

    public Answer<T> setData(T data) {
        this.data = data;
        return this;
    }
}

Is it possible to have both constructor in Lombok?

like image 678
barbara Avatar asked Sep 12 '14 13:09

barbara


1 Answers

Your class is equivalent to:

@Accessors(chain = true)
@Data    
@NoArgsConstructor
@AllArgsConstructor
public class Answer<T> {

    private T data;
}

Although strictly speaking this adds toString, equals and hashCode methods on all variables. This can (and often does) cause infinite loops. Be very wary of @Data.

@Accessors(chain = true) makes the setter implementations return this, more info here.

You can add multiple constructor annotations:

Unlike most other lombok annotations, the existence of an explicit constructor does not stop these annotations from generating their own constructor.

Note that @Accessors is experimental so may be changed/renamed at some future point.

I prefer @Builder to @AllArgsConstructor as it allows only required parameters to be set, whereas a all arguments constructor is all or nothing. It also generates much more readable code, consider

new Thing(true, 1, 4, false, 4, 4.0)

Versus

new Thing.Builder().
    setANamnedProperty(true).
    setAnotherNamnedProperty(1).
    ....
    build();
like image 153
Boris the Spider Avatar answered Oct 10 '22 01:10

Boris the Spider