如何在不获取“SomeType@2f92e0f4"的情况下打印我的 Java 对象? [英] How do I print my Java object without getting "SomeType@2f92e0f4"?
问题描述
我有一个类定义如下:
public class Person {私人字符串名称;//省略构造函数和getter/setter}
我试图打印我的类的一个实例:
System.out.println(myPerson);
但我得到以下输出:com.foo.Person@2f92e0f4
.
当我尝试打印一组 Person
对象时发生了类似的事情:
Person[] people =//...System.out.println(人);
我得到了输出:[Lcom.foo.Person;@28a418fc
这个输出是什么意思?如何更改此输出以使其包含我的人名?以及如何打印我的对象的集合?
注意:这是关于这个主题的规范问答.
背景
所有 Java 对象都有一个 toString()
方法,当您尝试打印对象时会调用该方法.
System.out.println(myObject);//调用 myObject.toString()
这个方法定义在Object
类(所有 Java 对象的超类).Object.toString()
方法返回一个相当难看的字符串,由类名、@
符号和 hashcode 以十六进制表示的对象.代码如下:
//Object.toString() 的代码公共字符串 toString() {return getClass().getName() + "@";+ Integer.toHexString(hashCode());}
诸如 com.foo.MyType@2f92e0f4
这样的结果可以解释为:
com.foo.MyType
- 类的名称,即类是com.foo
包中的MyType
.莉>@
- 将字符串连接在一起2f92e0f4
对象的哈希码.
数组类的名称看起来有点不同,这在Class.getName()
.例如,[Ljava.lang.String
表示:
[
- 一维数组(相对于[[
或[[[
等)L
- 数组包含一个类或接口java.lang.String
- 数组中对象的类型
自定义输出
要在调用 System.out.println(myObject)
时打印不同的内容,您必须override 你自己的类中的 toString()
方法.这是一个简单的例子:
public class Person {私人字符串名称;//省略构造函数和其他方法@覆盖公共字符串 toString() {返回名称;}}
现在如果我们打印一个Person
,我们会看到他们的名字而不是com.foo.Person@12345678
.
请记住,toString()
只是将对象转换为字符串的一种方式.通常,此输出应以清晰简洁的方式完整描述您的对象.对于我们的 Person
类来说,更好的 toString()
可能是:
@Override公共字符串 toString() {返回 getClass().getSimpleName() + [name=";+ 名称 + "]";}
哪个会打印,例如,Person[name=Henry]
.这是一个非常有用的调试/测试数据.
如果您只想关注对象的一个方面或包含大量爵士格式,则最好定义一个单独的方法,例如String toElegantReport() {...}
.
自动生成输出
许多 IDE 支持自动生成 toString()
方法,基于类中的字段.请参阅 Eclipse 和 IntelliJ.
一些流行的 Java 库也提供此功能.一些示例包括:
打印对象组
所以你已经为你的类创建了一个很好的 toString()
.如果将该类放入数组或集合中会发生什么?
数组
如果你有一个对象数组,你可以调用Arrays.toString()
生成数组内容的简单表示.例如,考虑这个 Person
对象数组:
Person[] people = { new Person(Fred"), new Person(Mike") };System.out.println(Arrays.toString(people));//打印:[弗雷德,迈克]
注意:这是对 Arrays 类中名为 toString()
的静态方法的调用,这与我们上面讨论的不同.>
如果你有一个多维数组,你可以使用Arrays.deepToString()
以实现相同类型的输出.
集合
大多数集合都会基于对每个元素调用 .toString()
产生漂亮的输出.
List人 = 新的 ArrayList<>();people.add(new Person(Alice"));people.add(new Person(Bob"));System.out.println(人);//打印 [Alice, Bob]
所以你只需要确保你的列表元素定义了一个很好的 toString()
,如上所述.
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
.
A similar thing happened when I tried to print an array of Person
objects:
Person[] people = //...
System.out.println(people);
I got the output: [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.
Background
All Java objects have a toString()
method, which is invoked when you try to print the object.
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:
// 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
- 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 array
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:
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
.
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:
@Override
public 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.
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:
@ToString
annotation from Project Lombok
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?
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:
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.
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.
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.
这篇关于如何在不获取“SomeType@2f92e0f4"的情况下打印我的 Java 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!