我如何打印我的java对象而不会获得“某种程度上”@2f92e0f4&quot&quot?

发布于 2025-02-08 06:19:45 字数 569 浏览 3 评论 0 原文

我有一个定义为以下类别的类:

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&

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

晌融 2025-02-15 06:19:46

我更喜欢使用使用 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);
    }
}

I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.

/**
 * 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);
    }
}
提赋 2025-02-15 06:19:46

默认情况下,Java中的每个对象都具有输出ObjectType@HashCode的 toString()方法。

如果您想要更多有意义的信息,则需要覆盖课堂中的 toString()方法。

public class Person {
  private String name;

  // constructor and getter/setter omitted

  // overridding toString() to print name
  public String toString(){
     return name;  
  }
}

现在,当您使用 system.out.prtinln(PersonoBj); 打印个人对象时,它将打印人的名称,而不是className和hashCode。

在您的第二种情况下,当您尝试打印数组时,它会打印 [lcom.foo.person;@28a418fc 数组类型和HashCode。


如果您想打印人的名字,则有很多方法。

您可以编写自己的功能,以迭代每个人并打印

void printPersonArray(Person[] persons){
    for(Person person: persons){
        System.out.println(person);
    }
}

您可以使用arrays.tostring()打印它。这对我来说似乎是最简单的。

 System.out.println(Arrays.toString(persons));
 System.out.println(Arrays.deepToString(persons));  // for nested arrays  

您可以将其打印为Java 8方法(使用流和方法参考)。

 Arrays.stream(persons).forEach(System.out::println);

可能还有其他方式。希望这会有所帮助。 :)

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.

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.

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

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.

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

 Arrays.stream(persons).forEach(System.out::println);

There might be other ways as well. Hope this helps. :)

慵挽 2025-02-15 06:19:46

在Intellij中,您可以通过按Alt+插图来自动生成ToString方法,然后选择ToString()这是一个用于测试类别的外数:

public class test  {
int a;
char b;
String c;
Test2 test2;

@Override
public String toString() {
    return "test{" +
            "a=" + a +
            ", b=" + b +
            ", c='" + c + '\'' +
            ", test2=" + test2 +
            '}';
 }
}

如您所见,它通过串联而生成一个字符串,该类别的几个属性,用于原始属性,用于原始词。将打印其值,对于参考类型,它将使用其类型(在这种情况下为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:

public class test  {
int a;
char b;
String c;
Test2 test2;

@Override
public 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).

佼人 2025-02-15 06:19:46

如果您直接打印任何人的对象,则将 className@hashcode 转移到代码。

在您的情况下, com.foo.person@2f92e0f4 正在打印。其中 person 是对象属于的类, 2f92e0f4 是对象的哈希码。

public class Person {
  private String name;

  public Person(String name){
  this.name = name;
  }
  // getter/setter omitted

   @override
   public String toString(){
        return name;
   }
}

现在,如果您尝试使用 person 的对象,那么它将打印名称

Class Test
 {
  public static void main(String... args){
    Person obj = new Person("YourName");
    System.out.println(obj.toString());
  }
}

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 . Where Person is a class to which object belongs and 2f92e0f4 is hashCode of the Object.

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

Class Test
 {
  public static void main(String... args){
    Person obj = new Person("YourName");
    System.out.println(obj.toString());
  }
}
稚气少女 2025-02-15 06:19:46

对于“ deep” toString()有一个基于JSON的答案(Jackson,Gson等)的替代方法: reflectionToStringBuilder 来自 apache commons lang 3 库,带有 recursivetoStringStyle Multilinerecursurecursivetostostostyle 。代码示例:

System.out.println("My object: " +
    ReflectionToStringBuilder
        .toString(theObject, new RecursiveToStringStyle()));

// or as "toString()" overrides

@Override
public String toString() {
  return ReflectionToStringBuilder
          .toString(this, new RecursiveToStringStyle());
}

// or

@Override
public String toString() {
  return ReflectionToStringBuilder
          .toString(this, new MultilineRecursiveToStringStyle());
}

输出示例:

// RecursiveToStringStyle
Person@7f54[name=Stephen,age=29,smoker=false,job=Job@43cd2[title=Manager]]

// MultilineRecursiveToStringStyle
Person@7f54[
  name=Stephen,
  age=29,
  smoker=false,
  job=Job@43cd2[
    title=Manager
  ]
]

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:

System.out.println("My object: " +
    ReflectionToStringBuilder
        .toString(theObject, new RecursiveToStringStyle()));

// or as "toString()" overrides

@Override
public String toString() {
  return ReflectionToStringBuilder
          .toString(this, new RecursiveToStringStyle());
}

// or

@Override
public String toString() {
  return ReflectionToStringBuilder
          .toString(this, new MultilineRecursiveToStringStyle());
}

Output examples:

// RecursiveToStringStyle
Person@7f54[name=Stephen,age=29,smoker=false,job=Job@43cd2[title=Manager]]

// MultilineRecursiveToStringStyle
Person@7f54[
  name=Stephen,
  age=29,
  smoker=false,
  job=Job@43cd2[
    title=Manager
  ]
]
安稳善良 2025-02-15 06:19:46

如果您查看对象类(Java中的所有类的父类),则toString()方法实现是

    public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

每当您打印Java中的任何对象时,则会调用ToString()。现在,如果您覆盖ToString(),则取决于您,那么您的方法将调用其他对象类方法调用。

If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is

    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.

倾其所爱 2025-02-15 06:19:46

在类上使用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.

御弟哥哥 2025-02-15 06:19:46

我设法使用 Jackson 在春季5中完成了此操作。根据对象,在所有情况下可能无法使用。

import com.fasterxml.jackson.databind.ObjectMapper;
    
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(yourObject));

输出看起来像:

{
  "id" : 1,
  "fieldOne" : "string"
}

在这里是使用 Jackson 的更多示例。

如果您使用 gson 相反,它可能看起来像:

Gson gson = new Gson();
System.out.println(gson.toJson(yourObject));

I managed to get this done using Jackson in Spring 5. Depending on the object it might not work in all cases.

import com.fasterxml.jackson.databind.ObjectMapper;
    
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(yourObject));

The output would look like:

{
  "id" : 1,
  "fieldOne" : "string"
}

Here are more examples using Jackson.

If you use GSON instead It might look like:

Gson gson = new Gson();
System.out.println(gson.toJson(yourObject));
汹涌人海 2025-02-15 06:19:46

如果您使用的是项目 Lombok ,则可以使用 @ToString 注释并生成标准 toString()方法,而无需添加样板。

import lombok.ToString;

@ToString
public class LoginDto {
  private String user;
  private String pass;
}
...
System.out.println(loginDto.toString());
// LoginDto([email protected], pass=xxxxx)

If you are using project Lombok you could use the @ToString annotation and generate a standard toString() method without adding boilerplate.

import lombok.ToString;

@ToString
public class LoginDto {
  private String user;
  private String pass;
}
...
System.out.println(loginDto.toString());
// LoginDto([email protected], pass=xxxxx)
锦上情书 2025-02-15 06:19:46

如果您不想覆盖 toString()方法,您

    public static void printJson(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

也需要导入,
导入com.fasterxml.jackson.databind.objectMapper;

我们可以制作一个Utils方法,这将非常方便。

If you don't want to Override the toString() method you can use this,

    public static void printJson(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

We also need to import,
import com.fasterxml.jackson.databind.ObjectMapper;

We can make a Utils method and it will be very handy.

潇烟暮雨 2025-02-15 06:19:46

只需使用Lombok Project的 @ToString 完成工作

Just use the @ToString from Lombok project gets the job done

画骨成沙 2025-02-15 06:19:46

有两种好方法可以做到这一点

  1. object.toString() - 对象类中toString()的默认实现返回一个由类名称, @ carame和未签名的六边形表示的字符串对象的哈希代码。例如, com.example.myclass@1a2b3c4d

在类中覆盖toString()方法以提供对象状态的字符串表示形式,这是一种常见的做法。

实现

public class MyClass {
    private int id;
    private String name;

    @Override
    public String toString() {
        return "MyClass{id=" + id + ", name='" + name + "'}";
    }
}

输出: myClass {id = 1,name ='test'}

  1. reflectionToStringBuilder.toString(object) -来自Apache Commons Lang库的ReflectionToStringBuilder使用反射来自动生成对象的所有字段的字符串表示,包括来自超级类别的继承字段。它提供了一种快速的方法来实现综合toString()方法,而无需手动编写每个字段的代码。

实现

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

public class MyClass {
    private int id;
    private String name;

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}

<代码>输出: com.example.myclass@1a2b3c4d [id = 1,name = test]

There are 2 good ways to do it

  1. 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

public class MyClass {
    private int id;
    private String name;

    @Override
    public String toString() {
        return "MyClass{id=" + id + ", name='" + name + "'}";
    }
}

Output: MyClass{id=1, name='Test'}

  1. 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

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

public class MyClass {
    private int id;
    private String name;

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}

Output: com.example.MyClass@1a2b3c4d[id=1,name=Test]

黯淡〆 2025-02-15 06:19:45

背景

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

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

此方法在 object 类(所有Java对象的超类)。 object.toString() 方法返回一个相当丑陋的字符串,由类的名称组成,@符号和 hashcode hashcode 十六进制中的对象。这样的代码看起来像:

// Code of Object.toString()
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(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()方法。这是一个简单的示例:

public class Person {

  private String name;
  
  // constructors and other methods omitted
  
  @Override
  public String toString() {
    return name;
  }
}

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

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

@Override
public String toString() {
  return getClass().getSimpleName() + "[name=" + name + "]";
}

哪个将打印,例如, person [name = henry] 。这是用于调试/测试的非常有用的数据。

如果您只想关注对象的一个​​方面或包含大量爵士格式,则最好定义单独的方法,例如字符串toelegantreport(){...}


自动生成输出

许多 ides> /代码>方法,基于类中的字段。请参阅 eclipse Intellijij ,例如。

几个受欢迎的Java库也提供了此功能。一些示例包括:


​如果将该类放入数组或集合中,会发生什么?

Arrays

If you have an array of objects, you can call

Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));

// Prints: [Fred, Mike]

注意:这是对 static 方法的调用,称为 toString()在数组类中,这与我们一直在讨论的内容不同。

如果您有多维数组,则可以使用 arrays.deeptoString() 以实现相同的输出。

收集

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

List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));    
System.out.println(people);

// Prints [Alice, Bob]

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

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 is MyType in the package com.foo.
  • @ - joins the string together
  • 2f92e0f4 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 interface
  • java.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:


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.

鱼忆七猫命九 2025-02-15 06:19:45

我认为Apache提供了一个更好的UTIT类,该类提供了获得字符串的功能

ReflectionToStringBuilder.toString(object)

I think apache provides a better util class which provides a function to get the string

ReflectionToStringBuilder.toString(object)
灰色世界里的红玫瑰 2025-02-15 06:19:45

Java中的每个类都有 toString()方法默认情况下,如果将该类的某些对象传递给 system.out.println(),则称为该类别。默认情况下,此调用返回该对象的className@HashCode。

{
    SomeClass sc = new SomeClass();
    // Class @ followed by hashcode of object in Hexadecimal
    System.out.println(sc);
}

您可以覆盖类的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);
    }
}

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.

{
    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

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);
    }
}
顾挽 2025-02-15 06:19:45

在日食中
上课,
右键单击 - &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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文