龙目岛各种建造者的注释?

bar*_*ara 14 java lombok

我上课了

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想简化Lombok.

如果我添加注释@AllArgsConstructor比我看不到默认构造函数.

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

    public Answer<T> setData(T data) {
        this.data = data;
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能同时拥有两个构造函数Lombok

Bor*_*der 26

你的班级相当于:

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

    private T data;
}
Run Code Online (Sandbox Code Playgroud)

虽然严格来说,这增加toString,equals以及hashCode对方法的所有变量.这可以(并且经常会)导致无限循环.要非常小心@Data.

@Accessors(chain = true)使setter实现返回this,更多信息在这里.

您可以添加多个构造函数注释:

与大多数其他lombok注释不同,显式构造函数的存在不会阻止这些注释生成自己的构造函数.

请注意,这@Accessors是实验性的,因此可能会在将来某个时候更改/重命名.

我更喜欢@Builder,@AllArgsConstructor因为它只允许设置所需的参数,而所有参数构造函数都是全有或全无.考虑,它还会生成更易读的代码

new Thing(true, 1, 4, false, 4, 4.0)
Run Code Online (Sandbox Code Playgroud)

new Thing.Builder().
    setANamnedProperty(true).
    setAnotherNamnedProperty(1).
    ....
    build();
Run Code Online (Sandbox Code Playgroud)

  • 我半推荐`@Accessors`赞成[配置](http://projectlombok.org/features/configuration.html).关于构造函数,我宁愿只使用`@ RequiredArgsConstructor`.结合Guice,这意味着,我只是声明一个字段并且可以使用它(代码中没有构造函数调用). (2认同)

vik*_*eve 11

你试过这个吗?

@NoArgsConstructor
@AllArgsConstructor
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,在我的情况下,这仅创建了第一个构造函数(无参数),而忽略了第二个构造函数。如果我翻转订单,问题也会翻转...... (3认同)