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
We can omit such fields simply by annotating them with the @ToString. Exclude annotation. In addition, Lombok output automatically excludes any variables starting with the $ symbol. However, we can override this behavior and include them by adding the @ToString.
Exclude indicates which fields have to be excluded in the string representation of the object. To exclude a field annotate the respective field with @ToString. Exclude .
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
If you want to skip some fields, you can annotate these fields with @ToString. Exclude . Alternatively, you can specify exactly which fields you wish to be used by using @ToString(onlyExplicitlyIncluded = true) , then marking each field you want to include with @ToString.
There is no way to change the format of the text which is printed. See the documentation.
The main goal 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 that.
There's an open ticket to provide more control over the format but it's been open for a while and that doesn't seem likely to change any time soon. I think the desire to implement that feature is there but writing an implementation which works for everyone is tricky so they're proceeding with caution.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With