Lombok之@ToString使用

x33g5p2x  于2021-12-25 转载在 其他  
字(4.8k)|赞(0)|评价(0)|浏览(338)

一. 为什么要用@ToString?

在java.lang.Object中有个实例方法toString,这个方法的作用是一个对象的自我描述。在源码中有这样一句注释,It is recommended that all subclasses override this method.即推荐所有的子类重新该方法。因为该方法在Object中的实现是返回字符串——类名和该对象的hashCode用“@”符连接起来的字符串,不具有可读性。所以,需要重写该方法,使得该方法能够清楚地表述自己的每一个成员变量。现在,我们在已经创建的Student类,重写该方法。

@Getter
@Setter
public class Student {

    private String name;

    private int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

可以看到重写后的方法占据了不小的篇幅,并且当我们新增一个成员变量后,需要再去维护这个方法的实现。那有没有这样一个注解,可以自动生成toString方法?答案就是@ToString。

二. @ToString如何使用?

@ToString的使用很简单,我们只需将它加到Student类上即可。

@Getter
@Setter
@ToString
public class Student {

    private String name;

    private int age;
}

测试使用

将项目使用maven编译后,再打开Student.class文件。

可以看到,反编译后的文件已经重写了toString方法。

三. @ToString源码

package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** * Generates an implementation for the {@code toString} method inherited by all objects, consisting of printing the values of relevant fields. * <p> * Complete documentation is found at <a href="https://projectlombok.org/features/ToString">the project lombok features page for &#64;ToString</a>. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface ToString {
	/** * Include the name of each field when printing it. * <strong>default: true</strong> * * @return Whether or not to include the names of fields in the string produced by the generated {@code toString()}. * 是否打印出字段名 */
	boolean includeFieldNames() default true;
	
	/** * Any fields listed here will not be printed in the generated {@code toString} implementation. * Mutually exclusive with {@link #of()}. * <p> * Will soon be marked {@code @Deprecated}; use the {@code @ToString.Exclude} annotation instead. * 不久后就被弃用,用@ToString.Exclude注解代替 * @return A list of fields to exclude. */
	String[] exclude() default {};
	
	/** * If present, explicitly lists the fields that are to be printed. * Normally, all non-static fields are printed. * <p> * Mutually exclusive with {@link #exclude()}. * <p> * Will soon be marked {@code @Deprecated}; use the {@code @ToString.Include} annotation together with {@code @ToString(onlyExplicitlyIncluded = true)}. * 不久后将被弃用,用@ToString.Include注解代替并且设置@ToString(onlyExplicitlyIncluded = true) * * @return A list of fields to use (<em>default</em>: all of them). */
	String[] of() default {};
	
	/** * Include the result of the superclass's implementation of {@code toString} in the output. * <strong>default: false</strong> * * @return Whether to call the superclass's {@code toString} implementation as part of the generated toString algorithm. */
	boolean callSuper() default false;
	
	/** * Normally, if getters are available, those are called. To suppress this and let the generated code use the fields directly, set this to {@code true}. * <strong>default: false</strong> * * @return If {@code true}, always use direct field access instead of calling the getter method. */
	boolean doNotUseGetters() default false;
	
	/** * Only include fields and methods explicitly marked with {@code @ToString.Include}. * Normally, all (non-static) fields are included by default. * * @return If {@code true}, don't include non-static fields automatically (default: {@code false}). * 如果为真,则不会自动将非静态的字段包含到toString方法中 */
	boolean onlyExplicitlyIncluded() default false;
	
	/** * If present, do not include this field in the generated {@code toString}. */
	@Target(ElementType.FIELD)
	@Retention(RetentionPolicy.SOURCE)
	public @interface Exclude {}
	
	/** * Configure the behaviour of how this member is rendered in the {@code toString}; if on a method, include the method's return value in the output. */
	@Target({ElementType.FIELD, ElementType.METHOD})
	@Retention(RetentionPolicy.SOURCE)
	public @interface Include {
// /** If true and the return value is {@code null}, omit this member entirely from the {@code toString} output. */
// boolean skipNull() default false; // -- We'll add it later, it requires a complete rework on the toString code we generate.
		
		/** * Higher ranks are printed first. Members of the same rank are printed in the order they appear in the source file. * * @return ordering within the generating {@code toString()}; higher numbers are printed first. */
		int rank() default 0;
		
		/** * Defaults to the field / method name of the annotated member. * If the name equals the name of a default-included field, this member takes its place. * * @return The name to show in the generated {@code toString()}. Also, if this annotation is on a method and the name matches an existing field, it replaces that field. */
		String name() default "";
	}
}

includeFieldNames参数默认值为true,可以为toString()方法的输出增加一些清晰度(即打印出字段名称)。

默认情况下,将打印所有非静态字段。如果要跳过某些字段,可以用注释这些字段@ToString.Exclude。另外,可以使用精确指定要被toString方法包含的字段,先设置@ToString(onlyExplicitlyIncluded = true),然后使用@ToString.Include标记每个要包含的字段。

通过设置callSuper为true,可以将超类实现toString的输出包含到输出中。请注意,toString()的默认实现java.lang.Object几乎没有意义,因此除非你主动继承了另一个类,否则你这样做没有意义。

您可以更改用于标识成员的名称@ToString.Include(name = “some other name”),name相当于给字段起别名;也可以通过更改成员的打印顺序@ToString.Include(rank = -1)。没有等级的成员被认为是等级0,等级数字大的成员首先被打印,等级相同的成员以它们在源文件中出现的顺序打印。

四. 特别说明

本文已经收录在Lombok注解系列文章总览中,并继承上文中所提的特别说明。
源码地址:gitee

相关文章