I have a class defined as follows:
我有一个类定义如下:
public class Person { private String name; // constructor and getter/setter omitted}
I tried to print an instance of my class:
我试图打印我的班级实例:
System.out.println(myPerson);
but I got the following output: com.foo.Person@2f92e0f4
.
但是我得到了以下输出:com.foo.Person@2f92e0f4。
A similar thing happened when I tried to print an array of Person
objects:
当我尝试打印Person对象数组时发生了类似的事情:
Person[] people = //...System.out.println(people);
I got the output: [Lcom.foo.Person;@28a418fc
我得到了输出:[Lcom.foo.Person; @ 28a418fc
What does this output mean? How do I change this output so it contains the name of my person? And how do I print collections of my objects?
这个输出是什么意思?如何更改此输出以使其包含我的人名?我如何打印我的对象集合?
Note: this is intended as a canonical Q&A about this subject.
注意:这是关于此主题的规范问答。
10 个解决方案
#1
Background
All Java objects have a toString()
method, which is invoked when you try and print the object.
所有Java对象都有一个toString()方法,当您尝试打印该对象时会调用该方法。
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object
class (the superclass of all Java objects). The Object.toString()
method returns a fairly ugly looking string, composed of the name of the class, an @
symbol and the hashcode of the object in hexadecimal. The code for this looks like:
此方法在Object类(所有Java对象的超类)中定义。 Object.toString()方法返回一个相当难看的字符串,由类的名称,@符号和十六进制的对象的哈希码组成。这个代码看起来像:
// Code of Object.toString()public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode());}
A result such as com.foo.MyType@2f92e0f4
can therefore be explained as:
因此,com.foo.MyType@2f92e0f4等结果可解释为:
-
com.foo.MyType
- the name of the class, i.e. the class isMyType
in the packagecom.foo
. -
@
- joins the string together -
2f92e0f4
the hashcode of the object.
com.foo.MyType - 类的名称,即com.foo包中的类是MyType。
@ - 将字符串连接在一起
2f92e0f4对象的哈希码。
The name of array classes look a little different, which is explained well in the Javadocs for Class.getName()
. For instance, [Ljava.lang.String
means:
数组类的名称看起来有点不同,这在Javadocs for Class.getName()中有很好的解释。例如,[Ljava.lang.String表示:
-
[
- an single-dimensional array (as opposed to[[
or[[[
etc.) -
L
- the array contains a class or interface -
java.lang.String
- the type of objects in the array
[ - 一维数组(与[[或[[[等]相反)
L - 数组包含类或接口
java.lang.String - 数组中对象的类型
Customizing the Output
To print something different when you call System.out.println(myObject)
, you must override the toString()
method in your own class. Here's a simple example:
要在调用System.out.println(myObject)时打印不同的内容,必须覆盖自己类中的toString()方法。这是一个简单的例子:
public class Person { private String name; // constructors and other methods omitted @Override public String toString() { return name; }}
Now if we print a Person
, we see their name rather than com.foo.Person@12345678
.
现在,如果我们打印一个人,我们会看到他们的名字,而不是com.foo.Person@12345678。
Bear in mind that toString()
is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString()
for our Person
class might be:
请记住,toString()只是将对象转换为字符串的一种方式。通常,此输出应以清晰简洁的方式完整描述您的对象。我们的Person类更好的toString()可能是:
@Overridepublic String toString() { return getClass().getSimpleName() + "[name=" + name + "]";}
Which would print, e.g., Person[name=Henry]
. That's a really useful piece of data for debugging/testing.
哪个会打印,例如Person [name = Henry]。这是用于调试/测试的非常有用的数据。
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}
.
如果您只想关注对象的一个方面或包含大量的爵士格式,您可能最好定义一个单独的方法,例如String toElegantReport(){...}。
Auto-generating the Output
Many IDEs offer support for auto-generating a toString()
method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
许多IDE支持基于类中的字段自动生成toString()方法。例如,请参阅Eclipse和IntelliJ的文档。
Several popular Java libraries offer this feature as well. Some examples include:
几个流行的Java库也提供此功能。一些例子包括:
-
ToStringBuilder
from Apache Commons Lang来自Apache Commons Lang的ToStringBuilder
-
MoreObjects.ToStringHelper
from Google Guava来自Google Guava的MoreObjects.ToStringHelper
-
@ToString
annotation from Project Lombok来自Project Lombok的@ToString注释
Printing groups of objects
So you've created a nice toString()
for your class. What happens if that class is placed into an array or a collection?
所以你为你的类创建了一个很好的toString()。如果将该类放入数组或集合中会发生什么?
Arrays
If you have an array of objects, you can call Arrays.toString()
to produce a simple representation of the contents of the array. For instance, consider this array of Person
objects:
如果您有一个对象数组,则可以调用Arrays.toString()来生成数组内容的简单表示。例如,考虑这个Person对象数组:
Person[] people = { new Person("Fred"), new Person("Mike") };System.out.println(Arrays.toString(people));// Prints: [Fred, Mike]
Note: this is a call to a static method called toString()
in the Arrays class, which is different to what we've been discussing above.
注意:这是对Arrays类中名为toString()的静态方法的调用,这与我们上面讨论的不同。
If you have a multi-dimensional array, you can use Arrays.deepToString()
to achieve the same sort of output.
如果你有一个多维数组,你可以使用Arrays.deepToString()来实现相同类型的输出。
Collections
Most collections will produce a pretty output based on calling .toString()
on every element.
大多数集合将基于在每个元素上调用.toString()来产生漂亮的输出。
List<Person> people = new ArrayList<>();people.add(new Person("Alice"));people.add(new Person("Bob")); System.out.println(people);// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString()
as discussed above.
所以你只需要确保你的列表元素定义一个很好的toString(),如上所述。
#2
I think apache provides a better util class which provides a function to get the string
我认为apache提供了一个更好的util类,它提供了获取字符串的函数
ReflectionToStringBuilder.toString(object)
#3
Every class in Java has the toString()
method in it by default, which is called if you pass some object of that class to System.out.println()
. By default, this call returns the className@hashcode of that object.
Java中的每个类都默认使用toString()方法,如果将该类的某个对象传递给System.out.println(),则会调用该方法。默认情况下,此调用返回该对象的className @ hashcode。
{ SomeClass sc = new SomeClass(); // Class @ followed by hashcode of object in Hexadecimal System.out.println(sc);}
You can override the toString method of a class to get different output. See this example
您可以覆盖类的toString方法以获得不同的输出。看这个例子
class A { String s = "I am just a object"; @Override public String toString() { return s; }}class B { public static void main(String args[]) { A obj = new A(); System.out.println(obj); }}
#4
In Eclipse,Go to your class,Right click->source->Generate toString()
;
在Eclipse中,转到您的类,右键单击 - > source-> Generate toString();
It will override the toString()
method and will print the object of that class.
它将覆盖toString()方法并将打印该类的对象。
#5
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
在intellij中,您可以通过按alt + inset自动生成toString方法,然后选择toString()这里是测试类的输出:
public class test {int a;char b;String c;Test2 test2;@Overridepublic String toString() { return "test{" + "a=" + a + ", b=" + b + ", c='" + c + '\'' + ", test2=" + test2 + '}'; }}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).
如您所见,它通过连接类的几个属性生成一个String,对于它将打印其值的基元,对于引用类型,它将使用它们的类类型(在本例中为Test2的字符串方法)。
#6
By default, every Object in Java has the toString()
method which outputs the ObjectType@HashCode.
默认情况下,Java中的每个Object都有toString()方法,该方法输出ObjectType @HashCode。
If you want more meaningfull information then you need to override the toString()
method in your class.
如果您想要更有意义的信息,那么您需要覆盖类中的toString()方法。
public class Person { private String name; // constructor and getter/setter omitted // overridding toString() to print name public String toString(){ return name; }}
Now when you print the person object using System.out.prtinln(personObj);
it will print the name of the person instead of the classname and hashcode.
现在,当您使用System.out.prtinln(personObj)打印person对象时;它将打印人的名称而不是类名和哈希码。
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc
the Array type and it's hashcode.
在第二种情况下,当您尝试打印数组时,它会打印[Lcom.foo.Person; @ 28a418fc数组类型及其哈希码。
If you want to print the person names, there are many ways.
如果要打印人名,有很多方法。
You could write your own function that iterates each person and prints
您可以编写自己的函数来迭代每个人并进行打印
void printPersonArray(Person[] persons){ for(Person person: persons){ System.out.println(person); }}
You could print it using Arrays.toString(). This seems the simplest to me.
您可以使用Arrays.toString()打印它。这对我来说似乎最简单。
System.out.println(Arrays.toString(persons)); System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
你可以用java 8方式打印它(使用流和方法引用)。
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
可能还有其他方式。希望这可以帮助。 :)
#7
If you Directly print any object of Person It will the ClassName@HashCode
to the Code.
如果直接打印Person的任何对象,它将ClassName @HashCode转换为Code。
in your case com.foo.Person@2f92e0f4
is getting printed . Where Person
is a class to which object belongs and 2f92e0f4
is hashCode of the Object.
在你的情况下,com.foo.Person@2f92e0f4正在打印。 Person是对象所属的类,2f92e0f4是Object的hashCode。
public class Person { private String name; public Person(String name){ this.name = name; } // getter/setter omitted @override public String toString(){ return name; }}
Now if you try to Use the object of Person
then it will print the name
现在,如果您尝试使用Person的对象,那么它将打印该名称
Class Test { public static void main(String... args){ Person obj = new Person("YourName"); System.out.println(obj.toString()); }}
#8
I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.
我更喜欢使用实用程序函数,该函数使用GSON将Java对象反序列化为JSON字符串。
/** * This class provides basic/common functionalities to be applied on Java Objects. */public final class ObjectUtils { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private ObjectUtils() { throw new UnsupportedOperationException("Instantiation of this class is not permitted in case you are using reflection."); } /** * This method is responsible for de-serializing the Java Object into Json String. * * @param object Object to be de-serialized. * @return String */ public static String deserializeObjectToString(final Object object) { return GSON.toJson(object); }}
#9
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
如果你看一下Object类(Java中所有类的Parent类),那么toString()方法实现就是
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
无论何时用Java打印任何对象,都会调用toString()。现在,如果你重写toString(),那么你的方法将调用其他的Object类方法调用。
#10
Arrays.deepToString(arrayOfObject)
Above function print array of object of different primitives.
上面的函数打印不同原语对象的数组。
[[AAAAA, BBBBB], [6, 12], [2003-04-01 00:00:00.0, 2003-10-01 00:00:00.0], [2003-09-30 00:00:00.0, 2004-03-31 00:00:00.0], [Interim, Interim], [2003-09-30, 2004-03-31]];
#1
Background
All Java objects have a toString()
method, which is invoked when you try and print the object.
所有Java对象都有一个toString()方法,当您尝试打印该对象时会调用该方法。
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object
class (the superclass of all Java objects). The Object.toString()
method returns a fairly ugly looking string, composed of the name of the class, an @
symbol and the hashcode of the object in hexadecimal. The code for this looks like:
此方法在Object类(所有Java对象的超类)中定义。 Object.toString()方法返回一个相当难看的字符串,由类的名称,@符号和十六进制的对象的哈希码组成。这个代码看起来像:
// Code of Object.toString()public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode());}
A result such as com.foo.MyType@2f92e0f4
can therefore be explained as:
因此,com.foo.MyType@2f92e0f4等结果可解释为:
-
com.foo.MyType
- the name of the class, i.e. the class isMyType
in the packagecom.foo
. -
@
- joins the string together -
2f92e0f4
the hashcode of the object.
com.foo.MyType - 类的名称,即com.foo包中的类是MyType。
@ - 将字符串连接在一起
2f92e0f4对象的哈希码。
The name of array classes look a little different, which is explained well in the Javadocs for Class.getName()
. For instance, [Ljava.lang.String
means:
数组类的名称看起来有点不同,这在Javadocs for Class.getName()中有很好的解释。例如,[Ljava.lang.String表示:
-
[
- an single-dimensional array (as opposed to[[
or[[[
etc.) -
L
- the array contains a class or interface -
java.lang.String
- the type of objects in the array
[ - 一维数组(与[[或[[[等]相反)
L - 数组包含类或接口
java.lang.String - 数组中对象的类型
Customizing the Output
To print something different when you call System.out.println(myObject)
, you must override the toString()
method in your own class. Here's a simple example:
要在调用System.out.println(myObject)时打印不同的内容,必须覆盖自己类中的toString()方法。这是一个简单的例子:
public class Person { private String name; // constructors and other methods omitted @Override public String toString() { return name; }}
Now if we print a Person
, we see their name rather than com.foo.Person@12345678
.
现在,如果我们打印一个人,我们会看到他们的名字,而不是com.foo.Person@12345678。
Bear in mind that toString()
is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString()
for our Person
class might be:
请记住,toString()只是将对象转换为字符串的一种方式。通常,此输出应以清晰简洁的方式完整描述您的对象。我们的Person类更好的toString()可能是:
@Overridepublic String toString() { return getClass().getSimpleName() + "[name=" + name + "]";}
Which would print, e.g., Person[name=Henry]
. That's a really useful piece of data for debugging/testing.
哪个会打印,例如Person [name = Henry]。这是用于调试/测试的非常有用的数据。
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}
.
如果您只想关注对象的一个方面或包含大量的爵士格式,您可能最好定义一个单独的方法,例如String toElegantReport(){...}。
Auto-generating the Output
Many IDEs offer support for auto-generating a toString()
method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
许多IDE支持基于类中的字段自动生成toString()方法。例如,请参阅Eclipse和IntelliJ的文档。
Several popular Java libraries offer this feature as well. Some examples include:
几个流行的Java库也提供此功能。一些例子包括:
-
ToStringBuilder
from Apache Commons Lang来自Apache Commons Lang的ToStringBuilder
-
MoreObjects.ToStringHelper
from Google Guava来自Google Guava的MoreObjects.ToStringHelper
-
@ToString
annotation from Project Lombok来自Project Lombok的@ToString注释
Printing groups of objects
So you've created a nice toString()
for your class. What happens if that class is placed into an array or a collection?
所以你为你的类创建了一个很好的toString()。如果将该类放入数组或集合中会发生什么?
Arrays
If you have an array of objects, you can call Arrays.toString()
to produce a simple representation of the contents of the array. For instance, consider this array of Person
objects:
如果您有一个对象数组,则可以调用Arrays.toString()来生成数组内容的简单表示。例如,考虑这个Person对象数组:
Person[] people = { new Person("Fred"), new Person("Mike") };System.out.println(Arrays.toString(people));// Prints: [Fred, Mike]
Note: this is a call to a static method called toString()
in the Arrays class, which is different to what we've been discussing above.
注意:这是对Arrays类中名为toString()的静态方法的调用,这与我们上面讨论的不同。
If you have a multi-dimensional array, you can use Arrays.deepToString()
to achieve the same sort of output.
如果你有一个多维数组,你可以使用Arrays.deepToString()来实现相同类型的输出。
Collections
Most collections will produce a pretty output based on calling .toString()
on every element.
大多数集合将基于在每个元素上调用.toString()来产生漂亮的输出。
List<Person> people = new ArrayList<>();people.add(new Person("Alice"));people.add(new Person("Bob")); System.out.println(people);// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString()
as discussed above.
所以你只需要确保你的列表元素定义一个很好的toString(),如上所述。
#2
I think apache provides a better util class which provides a function to get the string
我认为apache提供了一个更好的util类,它提供了获取字符串的函数
ReflectionToStringBuilder.toString(object)
#3
Every class in Java has the toString()
method in it by default, which is called if you pass some object of that class to System.out.println()
. By default, this call returns the className@hashcode of that object.
Java中的每个类都默认使用toString()方法,如果将该类的某个对象传递给System.out.println(),则会调用该方法。默认情况下,此调用返回该对象的className @ hashcode。
{ SomeClass sc = new SomeClass(); // Class @ followed by hashcode of object in Hexadecimal System.out.println(sc);}
You can override the toString method of a class to get different output. See this example
您可以覆盖类的toString方法以获得不同的输出。看这个例子
class A { String s = "I am just a object"; @Override public String toString() { return s; }}class B { public static void main(String args[]) { A obj = new A(); System.out.println(obj); }}
#4
In Eclipse,Go to your class,Right click->source->Generate toString()
;
在Eclipse中,转到您的类,右键单击 - > source-> Generate toString();
It will override the toString()
method and will print the object of that class.
它将覆盖toString()方法并将打印该类的对象。
#5
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
在intellij中,您可以通过按alt + inset自动生成toString方法,然后选择toString()这里是测试类的输出:
public class test {int a;char b;String c;Test2 test2;@Overridepublic String toString() { return "test{" + "a=" + a + ", b=" + b + ", c='" + c + '\'' + ", test2=" + test2 + '}'; }}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).
如您所见,它通过连接类的几个属性生成一个String,对于它将打印其值的基元,对于引用类型,它将使用它们的类类型(在本例中为Test2的字符串方法)。
#6
By default, every Object in Java has the toString()
method which outputs the ObjectType@HashCode.
默认情况下,Java中的每个Object都有toString()方法,该方法输出ObjectType @HashCode。
If you want more meaningfull information then you need to override the toString()
method in your class.
如果您想要更有意义的信息,那么您需要覆盖类中的toString()方法。
public class Person { private String name; // constructor and getter/setter omitted // overridding toString() to print name public String toString(){ return name; }}
Now when you print the person object using System.out.prtinln(personObj);
it will print the name of the person instead of the classname and hashcode.
现在,当您使用System.out.prtinln(personObj)打印person对象时;它将打印人的名称而不是类名和哈希码。
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc
the Array type and it's hashcode.
在第二种情况下,当您尝试打印数组时,它会打印[Lcom.foo.Person; @ 28a418fc数组类型及其哈希码。
If you want to print the person names, there are many ways.
如果要打印人名,有很多方法。
You could write your own function that iterates each person and prints
您可以编写自己的函数来迭代每个人并进行打印
void printPersonArray(Person[] persons){ for(Person person: persons){ System.out.println(person); }}
You could print it using Arrays.toString(). This seems the simplest to me.
您可以使用Arrays.toString()打印它。这对我来说似乎最简单。
System.out.println(Arrays.toString(persons)); System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
你可以用java 8方式打印它(使用流和方法引用)。
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
可能还有其他方式。希望这可以帮助。 :)
#7
If you Directly print any object of Person It will the ClassName@HashCode
to the Code.
如果直接打印Person的任何对象,它将ClassName @HashCode转换为Code。
in your case com.foo.Person@2f92e0f4
is getting printed . Where Person
is a class to which object belongs and 2f92e0f4
is hashCode of the Object.
在你的情况下,com.foo.Person@2f92e0f4正在打印。 Person是对象所属的类,2f92e0f4是Object的hashCode。
public class Person { private String name; public Person(String name){ this.name = name; } // getter/setter omitted @override public String toString(){ return name; }}
Now if you try to Use the object of Person
then it will print the name
现在,如果您尝试使用Person的对象,那么它将打印该名称
Class Test { public static void main(String... args){ Person obj = new Person("YourName"); System.out.println(obj.toString()); }}
#8
I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.
我更喜欢使用实用程序函数,该函数使用GSON将Java对象反序列化为JSON字符串。
/** * This class provides basic/common functionalities to be applied on Java Objects. */public final class ObjectUtils { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private ObjectUtils() { throw new UnsupportedOperationException("Instantiation of this class is not permitted in case you are using reflection."); } /** * This method is responsible for de-serializing the Java Object into Json String. * * @param object Object to be de-serialized. * @return String */ public static String deserializeObjectToString(final Object object) { return GSON.toJson(object); }}
#9
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
如果你看一下Object类(Java中所有类的Parent类),那么toString()方法实现就是
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
无论何时用Java打印任何对象,都会调用toString()。现在,如果你重写toString(),那么你的方法将调用其他的Object类方法调用。
#10
Arrays.deepToString(arrayOfObject)
Above function print array of object of different primitives.
上面的函数打印不同原语对象的数组。
[[AAAAA, BBBBB], [6, 12], [2003-04-01 00:00:00.0, 2003-10-01 00:00:00.0], [2003-09-30 00:00:00.0, 2004-03-31 00:00:00.0], [Interim, Interim], [2003-09-30, 2004-03-31]];