This article is a mirror article of machine translation, please click here to jump to the original article.

View: 15026|Reply: 5

[Source] Java about overriding toString() methods

[Copy link]
Posted on 2022-2-27 12:34:15 | | | |
Requirements: During the development process, all values of the object field need to be output to facilitate debugging and analysis problems. We can convert the object into a JSON string for output, or we can override the toString() method to output the object's value directly.

If the toString() method is not overridden, the system will call the toString() method of the object by default, and the output format is as follows:

<fully qualified class name>@<hash code of object in hexadecimal>
For example: Test@7a3d45bd
When an object overrides the toString() method, the rewritten method is called, as follows:



But by writing dead stitches like this return stringOne disadvantage is that when adding a field, you need to modify the toString() methodThis will be very troublesome. If there are many fields, a large number of "+" splicings will explode memory if the system memory is small (assuming that there are more system entities), because every "+" will new a String object.

using commons-lang3 packageToStringBuilderThese problems can be avoided very well. The Maven project is introduced as follows:


The sample code is as follows:

The renderings are as follows:



(End)





Previous:[Practical Training] Network Link Detection Tracert and TraceRoute tutorials
Next:Practical Operation: Use ProGet to build a NuGet private repository
Posted on 2022-2-28 19:51:30 |
Learn to learn...
Posted on 2022-5-22 22:57:06 |
Learn to learn:
Posted on 2022-5-23 16:31:09 |
Would it be better to use lombok?
Posted on 2023-2-13 11:46:54 |
Look good, encourage it
 Landlord| Posted on 2025-1-21 13:46:28 |
C# version:



Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com