Is it required to add toString() in all the POJO classes?
Its kind of a very basic question but I am worried about writing a piece of code in each n every POJO classes.
I have followed many java sources and I found a common things in those POJO classes-
@Override
public String toString() {
return StringUtil.toDetailString(this);
}
Is it required for serialisation or helps in performance improvement or something else?
It depends on what you're going to use the POJO for. In general, it's certainly not required. toString()
is not used in default Java binary serialization, although it may be used by some serialization frameworks. (I'm not aware of any that do this, but it's far from impossible.)
There's no performance benefit either.
There is potentially a diagnostic benefit though - that's the primary use of toString()
- to get a string representation for diagnostic purposes, whether in a debugger or when logging. In some cases you may also wish to rely on toString()
for non-diagnostic purposes, but you usually know about that when you do it... and normally such an implementation wouldn't just be StringUtil.toDetailString
- that sounds like it's just going to produce something possibly-JSON-like which is more aimed at developers than anything else.