In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this article Xiaobian for you to introduce in detail "how to gracefully print a Java object", the content is detailed, the steps are clear, the details are handled properly, I hope this "how to elegantly print a Java object" article can help you solve your doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.
The questioner defines a class like this:
Public class Cmower {private String name; public Cmower (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;}}
Then you create an object of this class and try to print it:
Cmower cmower = new Cmower ("Silent King II"); System.out.println (cmower)
But the result of the output is not what he wants:
Com.cmower.java_demo.stackoverflow.printObject.Cmower@355da254
In addition, he had a similar problem when printing arrays:
Cmower [] cmowers = {new Cmower (Silent King II), new Cmower (Silent King III)}; System.out.println (cmowers)
The output is as follows:
[Lcom.cmower.java_demo.stackoverflow.printObject.Cmower;@4dc63996
What does the output like Cmower@355da254 and [LCmower;@4dc63996] mean? How can I print out the name of the Cmower class? And how to print a list of objects (arrays or collections)?
If you have been plagued by such a problem, or are being troubled, please come with me, let's comb the question hand in hand and find a good answer. Duang, beat the monster to the next level!
What on earth happened?
All Java objects come with a toString () method by default, which is called when we try to print the object.
System.out.println (object); / / call object.toString ()
The toString () method is defined by the Object class (the superclass of all Java objects), which returns a string that looks obscure:
1) Class name, which consists of package name and class name, such as com.Cmower
2) @ Connector
3) hexadecimal hash code.
Take a look at the source code of this method:
Public String toString () {return getClass () .getName () + "@" + Integer.toHexString (hashCode ());}
Arrays are similar to normal Java objects, with only a slight difference-- as evidenced by the getName () method that tracks the Class class.
If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more'['characters representing the depth of the array nesting.
It roughly means that if it is an array, the Class name will be preceded by one or more parentheses "[", indicating the dimension of the array (one-dimensional array is one "[", two-dimensional array is two "["), followed by the type initials of an element.
This is why the prefix of the object array is "[L". Is there a feeling of sudden enlightenment?
02. Custom output
If you want to print your expected results, you must override the toString () method in your custom class to see the example.
Public class Cmower {private String name; / / omit constructor and getter/setter @ Override public String toString () {return name;}}
When we print the Cmower object again, the output is no longer com.Cmower@355da254.
Silent King two
But this result will not satisfy us, it is a bit abrupt, can not represent the type of object. A more elegant approach goes like this:
Public class Cmower {private String name; / / omit constructor and getter/setter @ Override public String toString () {return getClass () .getSimpleName () + "[name=" + name + "]";}}
Print the Cmower object again, and the output is as follows:
Cmower [name= Silence II]
This form not only looks beautiful, but also gives useful information when debugging. However, sometimes we don't want to override the toString () method (we want to keep the original print format ClassType@123121) and want to print information about the object, so it's best to define a new method, such as the toMyString () method.
03. Automatic output
IDE (Eclipse or Intellj IDEA) usually provides an output format for the fields of the class to override the toString () method.
@ Override public String toString () {return "Cmower {" + "name='" + name +'\'+'}';}
In addition, some open source third-party class libraries also provide such features, such as:
1) ToStringBuilder of Apache Commons Lang.
How to use it:
@ Override public String toString () {return ToStringBuilder.reflectionToString (this);}
Output result:
Com.cmower.printObject.Cmower@355da254 [name= Silence II]
2) MoreObjects of Google Guava
How to use it:
@ Override public String toString () {return MoreObjects.toStringHelper (this) .add ("name", getName ()) .toString ();}
Output result:
Cmower {name= Silent King II}
3) @ toString comment of Lombok (IDE needs to install the plug-in of Lombok first)
How to use it:
@ ToString public class Cmower {private String name; / / omit constructor and getter/setter}
All you need is an @ toString annotation, and you don't need to override the toString () method.
Output result:
Cmower (name= Silent King II)
04. Print a list of objects (array or collection)
The above has made it clear about printing a single object, are you ok? Next, let's talk about printing a list of objects.
1) Array
Arrays.toString () can convert any type of array to a string, including an array of primitive types and an array of reference types. The code example is as follows.
Cmower [] cmowers = {new Cmower (Silent King II), new Cmower (Silent King III)}; System.out.println (Arrays.toString (cmowers))
Output result:
[Cmower {name=' Silent King 2'}, Cmower {name=' Silent King 3'}]
2) set
For collections, we can print directly to output the results we expect. The code example is as follows.
List list = new ArrayList (); list.add (new Cmower); list.add (new Cmower); System.out.println (list)
Output result:
[Cmower {name=' Silent King 2'}, Cmower {name=' Silent King 3'}] here, this article "how to print a Java object gracefully" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it to understand it. If you want to know more about the article, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.