lombok 基础注解之 @ToString

最全的 lombok 注解详情(随着版本不定时更新)

一、注解介绍

作用于类,覆盖默认的 toString() 方法,输出格式:ClassName(fieldName=fieleValue, fieldName1=fieleValue)

二、属性介绍

  • includeFieldNames:在打印时是否包括字段的名称,默认为 true
  • exclude:通过该属性可以排除某些字段,默认为空
  • of:过该属性可以限定显示某些字段,默认打印非静态字段
    当 of 属性和 exclude 属性同时出现时,of 属性优先
    在不久的将来两者将会被加上 @Deprecated(不建议使用,有更好的替代),因为它们不能打印方法
  • callSuper:可以将父类的 toString 的输出包含到输出中(先调用),默认为 false
  • doNotUseGetters:是否调用 getter 方法获取属性值,false 表示调用,默认 false
  • onlyExplicitlyIncluded:仅包含显式标记为 @ToString.include 的字段和方法,默认为 false
  • Include:配置在中呈现此成员的方式;如果在方法上,则在输出中包含该方法的返回值,of 属性的替代
    Include 只有在 onlyExplicitlyIncluded = true 时才会生效,Include 标记在需要包含的属性或方法上
    当 onlyExplicitlyIncluded = true 时,则必须搭配 Include 使用,否则不打印任何字段
    • name:name 表示指定该字段的名称,默认为 “”
    • rank:rank 表示该字段的优先级,值越大排在越前面,默认为 0
  • Exclude:exclude 属性的替代
  • of、exclude 属性不能与 onlyExplicitlyIncluded、Include、Exclude 同时出现

三、实战演练

@ToString(
	includeFieldNames = true, exclude = {
    
    "age"}, of = {
    
    "name", "age"}, callSuper = false, doNotUseGetters = false
)
public class 佟丽娅 {
    
    
	private String name;
	
	private Integer age;
}
编译后
public class 佟丽娅 {
    
    
  	private String name;
  	
  	private Integer age;
	
  	public String toString() {
    
    
    	return "佟丽娅(name=" + this.name + ", age=" + this.age + ")";
  	}
}
@ToString(
	includeFieldNames = true, callSuper = false, doNotUseGetters = false,
	onlyExplicitlyIncluded = true // onlyExplicitlyIncluded 默认值为 false
)
public class 佟丽娅 {
    
    
	/**
	 * Include 需要配合 onlyExplicitlyIncluded = true 使用,否则无效
	 */
	@ToString.Include(name = "丫丫", rank = 0)	
	private String name;
	
	@ToString.Exclude
	private Integer age;
	
	@ToString.Include
	private String println() {
    
    
		return "佟丽娅";
	}
}
编译后
public class 佟丽娅 {
    
    
  	private String name;
  	
  	private Integer age;
	
	private String println() {
    
    
		return "佟丽娅";
	}
	
  	public String toString() {
    
    
    	return "佟丽娅(丫丫=" + this.name + ",println=" + println() + ")";
  	}
}

四、温馨提示

当 onlyExplicitlyIncluded = true 时需要搭配 @ToString.Include 使用,这个时候就没有必要用 @ToString.Exclude,因为字段不加 @ToString.Include 将都不会显示

猜你喜欢

转载自blog.csdn.net/qq_39249094/article/details/121134943