The @Tolerate
annotation is an experimental feature in lombok
where the target type is either a Method or a Constructor. The lombok website mentions as:
Any method or constructor can be annotated with @Tolerate and lombok will act as if it does not exist.
It states an example for a setter method:
@Setter
private Date date;
@Tolerate
public void setDate(String date) {
this.date = Date.valueOf(date);
}
In the above example if we had NOT added @Tolerate
, then lombok would NOT generate setDate(Date date)
because a method of the same name already exists (even though parameter type is different). So, how it works for a method is clear from this example.
But I am not able to understand how this annotation is to be used for a constructor.
@AllArgsConstructor
public class One {
private int id;
private String name;
// adding @Tolerate here does nothing.
public One(int a, int b) {
}
}
In the above code, lombok would generate an all argument constructor even if another constructor with the same number of parameters but different type exist.
So, how can we use @Tolerate
in the context of a constructor?
The @Data
, @Value
and @Builder
annotations create constructors (a constructor for all required arguments in the @Data
case, and a constructor for all arguments in the @Value
and @Builder
case). However, they do these only, if no other constructors exist. If you create your own constructor(s), @Data
, @Value
and @Builder
will not create their constructors, unless you annotate your own constructor(s) with @Tolerate
.
In a nutshell, @Tolerate
on a constructor only makes a difference, if you use it together with @Data
, @Value
or @Builder
. It has no effect, if you use it with @NoArgConstructor
, @AllArgsConstructor
or @RequiredArgsConstructor
, just like Gautham noticed.
Example:
@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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.