如何在构造函数上使用 lombok 的 @Tolerate

How to use lombok's @Tolerate on a constructor

@Tolerate 注释是 lombok 中的一项实验性功能,其中目标类型是方法或构造函数。龙目岛 website 提到为:

Any method or constructor can be annotated with @Tolerate and lombok will act as if it does not exist.

它陈述了一个 setter 方法的例子:

@Setter
private Date date;

@Tolerate
public void setDate(String date) {
    this.date = Date.valueOf(date);
}

在上面的例子中如果我们没有添加 @Tolerate,那么lombok会NOT生成setDate(Date date)因为已经存在同名方法(即使参数类型不同)。 因此,从这个例子中可以清楚地看出方法是如何工作的。

但我无法理解如何将此注释用于构造函数。

@AllArgsConstructor
public class One {
    private int id;
    private String name;

    // adding @Tolerate here does nothing. 
    public One(int a, int b) {
    }
}

在上面的代码中,lombok 将生成一个全参数构造函数,即使存在另一个具有相同数量的参数但不同类型的构造函数。

那么,我们如何在构造函数的上下文中使用 @Tolerate

@Data@Value@Builder 注释创建构造函数(@Data 情况下所有必需参数的构造函数,以及@Value@Builder 案例)。但是,如果不存在其他构造函数,它们只会执行这些操作。如果您创建自己的构造函数,@Data@Value@Builder 将不会创建它们的构造函数,除非您使用 @Tolerate 注释您自己的构造函数。

简而言之,构造函数上的 @Tolerate 只有在与 @Data@Value@Builder 一起使用时才会有所不同。它没有效果,如果你将它与 @NoArgConstructor@AllArgsConstructor@RequiredArgsConstructor 一起使用,就像 Gautham 注意到的那样。

示例:

@Value
public class Main {
    private int id;
    private String name;
    
    @Tolerate // Now the allArgsConstructor will be created. If you omit the annotation, no allArgsConstructor will be created.
    public Main(String name) {
        this.name = name;
        this.id = 0;
    }
}