本文介绍了如何在不获取“SomeType @ 2f92e0f4”的情况下打印我的Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下定义的类:

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);

但我得到以下输出: com.foo.Person@2f92e0f4

but I got the following output: com.foo.Person@2f92e0f4.

当我尝试打印 Person 对象的数组时,发生了类似的事情:

A similar thing happened when I tried to print an array of Person objects:

Person[] people = //...
System.out.println(people); 

我得到了输出: [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?

推荐答案

背景



所有Java对象都有 toString()方法,在您尝试打印对象时调用。

Background

All Java objects have a toString() method, which is invoked when you try and print the object.

System.out.println(myObject);  // invokes myObject.toString()

此方法在 class(所有Java对象的超类)。 方法返回一个相当难看的字符串,由类的名称, @ 符号和哈希码。代码如下:

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());
}

结果如 com.foo.MyType @ 2f92e0f4 因此可以解释为:

A result such as com.foo.MyType@2f92e0f4 can therefore be explained as:


  • com.foo.MyType - 类的名称,即包 com.foo 中的类 MyType

  • @ - 将字符串连接在一起

  • 2f92e0f4 对象的哈希码。

  • com.foo.MyType - the name of the class, i.e. the class is MyType in the package com.foo.
  • @ - joins the string together
  • 2f92e0f4 the hashcode of the object.

数组类的名称看起来有点不同,这在Javadocs中有很好的解释对于。例如, [Ljava.lang.String 表示:

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:


  • [ - 一维数组(而不是 [[ [[[等。)

  • L - 数组包含类或接口

  • java.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

在调用 System.out.println(myObject)时打印不同的内容,你必须 toString()您自己班级中的方法。这是一个简单的例子:

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;
  }
}

现在,如果我们打印,我们看到他们的名字而不是 com.foo.Person@12345678

Now if we print a Person, we see their name rather than com.foo.Person@12345678.

请记住, toString()只是一种方式,可以将对象转换为字符串。通常,此输出应以清晰简洁的方式完整地描述您的对象。对于我们的 Person 类,更好的 toString()可能是:

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 + "]";
}

会打印哪个,例如 Person [name =亨利] 。这是用于调试/测试的非常有用的数据。

Which would print, e.g., Person[name=Henry]. That's a really useful piece of data for debugging/testing.

如果你只想关注对象的一个​​方面或包含大量的爵士格式,你可能会更好地定义一个单独的方法,例如 String toElegantReport(){...}

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() {...}.

许多提供支持,根据类中的字段自动生成 toString()方法。请参阅和。

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.

几个流行的Java库也提供此功能。一些例子包括:

Several popular Java libraries offer this feature as well. Some examples include:


  • http://commons.apache.org/proper/commons-lang/rel =noreferrer> Apache Commons Lang

的.ToStringHelper

MoreObjects.ToStringHelper from Google Guava

的注释

@ToString annotation from Project Lombok

所以你创造了一个不错的 toString()为您的班级。如果将该类放入数组或集合中会发生什么?

So you've created a nice toString() for your class. What happens if that class is placed into an array or a collection?

如果您有一个数组对象,您可以调用生成数组内容的简单表示。例如,考虑这个 Person 对象的数组:

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]

注意:这是在Arrays类中调用名为 toString()静态方法,这与我们上面讨论的不同。

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.deepToString() 实现相同类型的输出。

If you have a multi-dimensional array, you can use Arrays.deepToString() to achieve the same sort of output.

大多数集合将根据调用产生漂亮的输出每个元素上的 .toString()

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]

所以你只需要确保你的列表元素定义了一个不错的 toString(),如上所述。

So you just need to ensure your list elements define a nice toString() as discussed above.

这篇关于如何在不获取“SomeType @ 2f92e0f4”的情况下打印我的Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:38