We have a lot of objects for which we like to implement a simple toString
to output attributes of the object. Some of these attributes may be complex objects themselves.
Is there any standard, or simply just a best practice for a style? I'm thinking something like:
[SimpleClassName] { prop1:value, prop2:value }
In which case a nested value would look like:
[SimpleClassName] { prop1:value, prop2:[NestedObject] { prop3:value}}
We are using Java but I find myself asking the same question in most languages!
By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called. Here are some of the advantages of using this method.
What is toString()? 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.
toString() is supposed to return a string containing a "description" of the object. It's not supposed to print anything.
I think the format produced by Guava's MoreObjects.toStringHelper() is pretty nice, but it's mainly just good to have some consistent format that you use:
public String toString() { return Objects.toStringHelper(this) .add("prop1", prop1) .add("prop2", prop2) .toString(); } // Produces "SimpleClassName{prop1=foo, prop2=bar}"
Personally, I find the mix of []
and {}
not so easy to get an immediate view of the hierarchy.
I like this format (and I've seen it being used in a number of places):
SimpleClassName[prop1=value, prop2=value] SimpleClassName[prop1=value, prop2=NestedObject[prop3=value]]
There's also the possibility to add an identifier with @
, for example the default style for the commons-lang ToStringBuilder
does that (using its own example):
Person@182f0db[name=John Doe,age=33,smoker=false]
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