Automate tostring () Creation

Source: Internet
Author: User
Experienced Java developers know that it is important to write the tostring method. It is quite easy to record and debug objects that can be viewed in the form of human understanding, especially when dealing with distributed applications. Unfortunately, implementing the tostring Method for many classes can be quite time consuming-especially for classes with many attributes. Because the tostring behavior is quite regular, it is best to make the task of creating this method automatically complete. The utility provided in this Article can help you achieve this and reduce the burden on your development.
Developers involved in large projects usually spend several hours writing useful tostring methods. Even if each class does not provide its own tostring method, each data container must have its own tostring method. It may be confusing for every developer to write the tostring method in their own way. Every developer will undoubtedly propose a unique format. As a result, the use of such output in the debugging process adds unnecessary trouble, and there is no benefit. Therefore, each project should define a single format for the tostring method and automate their creation.
Automate tostring Creation
The following shows a utility that you can use to automatically create a tostring. This tool automatically generates a rule-based, strong tostring method for the specified class, almost eliminating the time used to develop this method. It also centrally manages the tostring () format. If you have changed the format, you must regenerate the tostring method. However, this is much easier than Manually changing hundreds of classes.

It is also easy to maintain the generated code. If you add more attributes to the class, you may also need to modify the tostring method. Because the tostring method is automatically generated, you only need to run this utility on the class again to complete the change. This is simpler than the manual method and less likely to make mistakes.

This article does not explain reflection API; the following code assumes that you have understood the basic concepts of reflection. To view the reflection API documentation, visit the reference resources section. The source code of the utility is as follows:

Package Fareed. Publications. utilities;
Import java. Lang. Reflect .*;

Public class tostringgenerator
Public static void main (string [] ARGs)
If (ARGs. Length = 0)
System. Out. println ("provide the class name as the command line argument ");
System. Exit (0 );

Try {

Class targetclass = Class. forname (ARGs [0]);

If (! Targetclass. isprimitive () & targetclass! = String. Class)
Field fields [] = targetclass. getdeclaredfields ();

Class csuper = targetclass. getsuperclass (); // retrieves a superclass

Output ("stringbuffer buffer = new stringbuffer (500);"); // construct a buffer

If (csuper! = NULL & csuper! = Object

For (Int J = 0; j <fields. length; j ++ ){
Output ("buffer. append (/" "+ fields [J]. getname () +" =/");"); // additional domain name

If (fields [J]. GetType (). isprimitive () | fields [J]. GetType () = string. Class) // check the basic data type or string type
Output ("buffer. append (this." + fields [J]. getname () + ");"); // attaches the value of the basic data type field
/* It is not a basic data type field, so you need to check the null value of the clustered object */
Output ("If (this." + fields [J]. getname () + "! = NULL )");
Output ("buffer. append (this." + fields [J]. getname () + ". tostring ());");
Output ("else buffer. append (/" value is null /");");
} // Else ends
} // The End of the loop
Output ("Return buffer. tostring ();");
} Catch (classnotfoundexception e ){
System. Out. println ("class not found in the class path ");
System. Exit (0 );

Private Static void output (string data)
System. Out. println (data );


Code output channel
The code format also depends on your project tool requirements. Some developers may like to save the code to a user-defined file on the disk. Other developers are very satisfied with the system. out console. They can use the console to manually copy or embed the code into actual files. I will leave these options to you. This article only uses the simplest method: system. Out statement.

Limitations of this method
This method has two obvious limitations. The first limitation is that it does not support loop inclusion of objects. If object A contains a reference of object B and object B contains a reference of object A, this tool cannot be processed. However, this is rare for many projects.

The second limitation is that the tostring method must be regenerated after the member variables are added or removed. This step must be completed no matter whether the tool is used or not, so this is not a problem specific to the tool.

In this article, I illustrate a small automatic utility that can really improve the efficiency of developers. It plays a very small but important role in the entire project.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.