如何以正确的方式打印对象内容? [英] How to print object content in correct way?

查看:133
本文介绍了如何以正确的方式打印对象内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList ,其中包含来自 User 类的一些对象。当我打印这些对象时,我得到了:

I have an ArrayList that contains some objects from User class. When I print these objects I got:


[User @ 18fd984,User @ 18fd984]

[User@18fd984, User@18fd984]

如何以正确的方式打印这些对象?

How to print these objects in a correct way?

推荐答案

覆盖方法类中的 toString 用于生成您喜欢的输出,而不是Java自动生成的默认值。示例:

Override the method toString in the class to produce the output you prefer, instead of the default value that Java automatically generates. Example:

public class User {
   private String name;
   ...
   @Override
   public String toString() {
       return name;
   }
}

对于复杂对象,Apache Commons Lang 提供了一些方便的方法:

For complex objects, Apache Commons Lang provides some handy methods, if you are already using this dependency in your project:

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

这篇关于如何以正确的方式打印对象内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆