简体   繁体   中英

How to change the output of the method generated by Lombok's @ToString?

If we use Lombok's @ToString , for example as part of @Data , the output format is hard to read:

@Data
class Test {
    int a;
    int b;
}

Test test = new Test(1, 2);
System.out.println(test.toString());

This results in the following output:

a=1, b=2

Would it be possible to print it like this instead? If the structure of class is highly nested with maps and lists, it is really hard to read it.

a=1,
b=2

There is no way to change the format of the text which is printed. See the documentation .

The whole point of that annotation is to give you a quick and easy way to generate a method that you can use for logging etc. It's not designed to be all-purpose.

If you wanted to implement your own functionality across multiple classes, you could use aspect-oriented programming to accomplish this.

Unfurttenly lombok doesn't come with that feature, however, is possible achieve it by using other libraries like commons-lang3 .

Decoupled solution , class and serializer are not tied.

System.out.println(ToStringBuilder.reflectionToString(test, ToStringStyle.MULTI_LINE_STYLE));

Coupled solution

class Test {
    private final int a;
    private final int b;

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }
}

call serializer:

System.out.println(test.toString());

Be aware that if you use this solution, could be conflict with @Data on ToString method, so to avoid that must use underhood(@Getter, @Setter, @RequiredArgsConstructor, ...) annotations instead os @Data.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM