要在使用Lombok的@ToString注解时跳过空字段,您需要将@ToString.Include
注解与@ToString
一起使用,并在其中配置onlyExplicitlyIncluded = true
,然后分别为需要包含的字段添加@ToString.Include
注解
以下是一个例子:
import lombok.ToString;
@ToString(onlyExplicitlyIncluded = true)
public class Person {
@ToString.Include(name = "name", whenNotNull = true)
private String name;
@ToString.Include(name = "age", whenNotNull = true)
private Integer age;
@ToString.Include(name = "address", whenNotNull = true)
private String address;
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
person.setAge(null);
person.setAddress("北京");
System.out.println(person);
}
// 省略getter和setter方法
}
在这个例子中,我们分别对name、age和address字段添加了@ToString.Include注解,并设置了whenNotNull = true
。这将在生成toString方法时跳过空(null)字段。
当运行上面的main方法时,将输出以下结果:
Person(name=张三, address=北京)
可以看到age字段由于为null,因此在生成的toString方法中被跳过了。
领取专属 10元无门槛券
手把手带您无忧上云