我如何打印我的java对象而不会获得“某种程度上”@2f92e0f4&quot&quot?
我有一个定义为以下类别的类:
public class Person {
private String name;
// constructor and getter/setter omitted
}
我尝试打印一个类的实例:
System.out.println(myPerson);
但是我得到了以下输出: com.foo.person@2f92e0f4
。
当我尝试打印 Person
对象的数组时,也发生了类似的事情:
Person[] people = //...
System.out.println(people);
我得到了输出: [lcom.foo.person;@28A418FC
此输出是什么意思?如何更改此输出,以包含我的人的名字?以及如何打印物体的集合?
注意:这是针对此主题的规范Q&
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
我更喜欢使用使用 gson 将Java对象删除到JSON字符串中的实用程序函数。
I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.
默认情况下,Java中的每个对象都具有输出ObjectType@HashCode的
toString()
方法。如果您想要更多有意义的信息,则需要覆盖课堂中的
toString()
方法。现在,当您使用
system.out.prtinln(PersonoBj);
打印个人对象时,它将打印人的名称,而不是className和hashCode。在您的第二种情况下,当您尝试打印数组时,它会打印
[lcom.foo.person;@28a418fc
数组类型和HashCode。如果您想打印人的名字,则有很多方法。
您可以编写自己的功能,以迭代每个人并打印
您可以使用arrays.tostring()打印它。这对我来说似乎是最简单的。
您可以将其打印为Java 8方法(使用流和方法参考)。
可能还有其他方式。希望这会有所帮助。 :)
By default, every Object in Java has the
toString()
method which outputs the ObjectType@HashCode.If you want more meaningfull information then you need to override the
toString()
method in your class.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.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.If you want to print the person names, there are many ways.
You could write your own function that iterates each person and prints
You could print it using Arrays.toString(). This seems the simplest to me.
You could print it the java 8 way (using streams and method reference).
There might be other ways as well. Hope this helps. :)
在Intellij中,您可以通过按Alt+插图来自动生成ToString方法,然后选择ToString()这是一个用于测试类别的外数:
如您所见,它通过串联而生成一个字符串,该类别的几个属性,用于原始属性,用于原始词。将打印其值,对于参考类型,它将使用其类型(在这种情况下为test2的字符串方法)。
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:
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).
如果您直接打印任何人的对象,则将
className@hashcode
转移到代码。在您的情况下,
com.foo.person@2f92e0f4
正在打印。其中person
是对象属于的类,2f92e0f4
是对象的哈希码。现在,如果您尝试使用
person
的对象,那么它将打印名称If you Directly print any object of Person It will the
ClassName@HashCode
to the Code.in your case
com.foo.Person@2f92e0f4
is getting printed . WherePerson
is a class to which object belongs and2f92e0f4
is hashCode of the Object.Now if you try to Use the object of
Person
then it will print the name对于“ deep”
toString()
有一个基于JSON的答案(Jackson,Gson等)的替代方法: reflectionToStringBuilder 来自 apache commons lang 3 库,带有 recursivetoStringStyle 或 Multilinerecursurecursivetostostostyle 。代码示例:输出示例:
For a "deep"
toString()
there is an alternative to the JSON based answers (Jackson, GSON, etc.): ReflectionToStringBuilder from the Apache Commons Lang 3 library, with RecursiveToStringStyle or MultilineRecursiveToStringStyle. Code example:Output examples:
如果您查看对象类(Java中的所有类的父类),则toString()方法实现是
每当您打印Java中的任何对象时,则会调用ToString()。现在,如果您覆盖ToString(),则取决于您,那么您的方法将调用其他对象类方法调用。
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
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.
在类上使用Lombok @Data注释将提供Getter,Setter,Tostring和Hashcode。在处理样板代码时,使用Lombok更好。
Using Lombok @Data annotation on class will provide getter, setter, toString and hashcode. Using Lombok is better as it handles boilerplate code.
我设法使用 Jackson 在春季5中完成了此操作。根据对象,在所有情况下可能无法使用。
输出看起来像:
在这里是使用 Jackson 的更多示例。
如果您使用 gson 相反,它可能看起来像:
I managed to get this done using Jackson in Spring 5. Depending on the object it might not work in all cases.
The output would look like:
Here are more examples using Jackson.
If you use GSON instead It might look like:
如果您使用的是项目 Lombok ,则可以使用
@ToString
注释并生成标准toString()
方法,而无需添加样板。If you are using project Lombok you could use the
@ToString
annotation and generate a standardtoString()
method without adding boilerplate.如果您不想覆盖
toString()
方法,您也需要导入,
导入com.fasterxml.jackson.databind.objectMapper;
我们可以制作一个Utils方法,这将非常方便。
If you don't want to Override the
toString()
method you can use this,We also need to import,
import com.fasterxml.jackson.databind.ObjectMapper;
We can make a Utils method and it will be very handy.
只需使用Lombok Project的
@ToString
完成工作Just use the
@ToString from Lombok project
gets the job done有两种好方法可以做到这一点
object.toString()
- 对象类中toString()的默认实现返回一个由类名称, @ carame和未签名的六边形表示的字符串对象的哈希代码。例如, com.example.myclass@1a2b3c4d 。在类中覆盖toString()方法以提供对象状态的字符串表示形式,这是一种常见的做法。
实现
输出:
myClass {id = 1,name ='test'}
实现
<代码>输出:
com.example.myclass@1a2b3c4d [id = 1,name = test]
There are 2 good ways to do it
object.toString()
- The default implementation of toString() in the Object class returns a string consisting of the class name, the @ character, and the unsigned hexadecimal representation of the hash code of the object. For example, com.example.MyClass@1a2b3c4d.It's a common practice to override the toString() method in classes to provide a string representation of the object's state.
Implementation
Output:
MyClass{id=1, name='Test'}
ReflectionToStringBuilder.toString(object)
- The ReflectionToStringBuilder from the Apache Commons Lang library uses reflection to automatically generate a string representation of all fields of an object, including inherited fields from superclasses. It provides a quick way to implement a comprehensive toString() method without manually writing the code for each field.Implementation
Output:
com.example.MyClass@1a2b3c4d[id=1,name=Test]
背景
所有Java对象都有
toString()
方法,当您尝试打印对象时会调用。此方法在
object
类(所有Java对象的超类)。
object.toString()
方法返回一个相当丑陋的字符串,由类的名称组成,@
符号和 hashcode hashcode 十六进制中的对象。这样的代码看起来像:诸如
com.foo.mytype@2f92e0f4
之类的结果可以解释为:com.foo.mytype
- 类的名称,类的名称, IE类是myType
在软件包com.foo
中。@
- 将字符串加入2f92e0f4
对象的哈希码。数组类的名称看起来有些不同,在Javadocs中很好地解释 - “ rel =“ noreferrer”>
class.getName()
。例如,[ljava.lang.string
含义:[
- 一个单维数组(而不是[[
或或
[ [[
等)l
- 数组包含类或接口java.lang.string
- 数组中的对象类型自定义输出
以打印输出呼叫
system.out.println(myObject)
时,有所不同,您必须覆盖您自己的类中的toString()
方法。这是一个简单的示例:现在,如果我们打印一个
Person
,我们会看到他们的名字而不是com.foo.person@12345678
。请记住,
toString()
只是一种的方法,将对象转换为字符串。通常,此输出应以清晰而简洁的方式充分描述您的对象。更好的toString()
我们的person
类可能是:哪个将打印,例如,
person [name = henry]
。这是用于调试/测试的非常有用的数据。如果您只想关注对象的一个方面或包含大量爵士格式,则最好定义单独的方法,例如
字符串toelegantreport(){...}
。自动生成输出
许多 ides> /代码>方法,基于类中的字段。请参阅 eclipse 和 Intellijij ,例如。
几个受欢迎的Java库也提供了此功能。一些示例包括:
toStringBuilder
来自来自 google guava
@tostring
来自项目Lombok
如果将该类放入数组或集合中,会发生什么?
Arrays
If you have an array of objects, you can call
注意:这是对 static 方法的调用,称为
toString()
在数组类中,这与我们一直在讨论的内容不同。如果您有多维数组,则可以使用
arrays.deeptoString()
以实现相同的输出。收集
大多数集合将根据调用
.toString()
在每个元素上产生一个漂亮的输出。因此,您只需要确保列表元素定义一个不错的
toString()
,如上所述。Background
All Java objects have a
toString()
method, which is invoked when you try to print the object.This method is defined in the
Object
class (the superclass of all Java objects). TheObject.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:A result such as
com.foo.MyType@2f92e0f4
can therefore be explained as:com.foo.MyType
- the name of the class, i.e. the class isMyType
in the packagecom.foo
.@
- joins the string together2f92e0f4
the hashcode of the object.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:[
- an single-dimensional array (as opposed to[[
or[[[
etc.)L
- the array contains a class or interfacejava.lang.String
- the type of objects in the arrayCustomizing the Output
To print something different when you call
System.out.println(myObject)
, you must override thetoString()
method in your own class. Here's a simple example:Now if we print a
Person
, we see their name rather thancom.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 bettertoString()
for ourPerson
class might be:Which would print, e.g.,
Person[name=Henry]
. That's a really useful piece of data for debugging/testing.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() {...}
.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.Several popular Java libraries offer this feature as well. Some examples include:
ToStringBuilder
from Apache Commons LangMoreObjects.ToStringHelper
from Google Guava@ToString
annotation from Project LombokPrinting 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?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 ofPerson
objects: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.If you have a multi-dimensional array, you can use
Arrays.deepToString()
to achieve the same sort of output.Collections
Most collections will produce a pretty output based on calling
.toString()
on every element.So you just need to ensure your list elements define a nice
toString()
as discussed above.我认为Apache提供了一个更好的UTIT类,该类提供了获得字符串的功能
I think apache provides a better util class which provides a function to get the string
Java中的每个类都有
toString()
方法默认情况下,如果将该类的某些对象传递给system.out.println()
,则称为该类别。默认情况下,此调用返回该对象的className@HashCode。您可以覆盖类的ToString方法以获取不同的输出。请参阅此示例
Every class in Java has the
toString()
method in it by default, which is called if you pass some object of that class toSystem.out.println()
. By default, this call returns the className@hashcode of that object.You can override the toString method of a class to get different output. See this example
在日食中
上课,
右键单击 - &gt; source-&gt;生成
toString()
;它将覆盖
toString()
方法,并将打印该类的对象。In Eclipse,
Go to your class,
Right click->source->Generate
toString()
;It will override the
toString()
method and will print the object of that class.