什么时候应该覆盖toString()? [英] When should I override toString()?

查看:153
本文介绍了什么时候应该覆盖toString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Javadocs说


返回对象的字符串表示形式。通常,
toString方法返回一个文本表示此
对象的字符串。结果应该是一个简洁但信息丰富的表示
,一个人很容易阅读。建议所有
子类重写此方法。

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

但是我什么时候应该花时间覆盖 toString 我班级的方法?它应该是我做的第一件事,其中重写等于 hashCode ?或者我应该等到实际需要它?

But when should I spend time overriding the toString method for my classes? Should it be one of the first things I do along with overriding equals and hashCode? Or should I wait until it's actually needed?

我知道Eclipse可以为你自动生成 toString 方法,所以我应该让Eclipse自动生成它们一次知道我班级的字段吗?

I know Eclipse can auto generate toString methods for you, so should I just have Eclipse auto generate them once I know the fields for my class?

推荐答案

Josh Bloch在 Effective Java ,在第10项中。

Josh Bloch gives a good explanation in Effective Java, in item 10.


[ ...]提供良好的toString实现使您的类使用起来更加愉快。

[...] providing a good toString implementation makes your class much more pleasant to use.

它确实更容易输出调试跟踪,或者制作更好的日志消息,因为您可以直接使用 toString()提供的对象的字符串表示形式;您不必手动构建一个字符串来提供对象所需的信息。

It really makes it easier to output debugging traces, or makes better logging messages, since you can use the object's string representation provided by toString() directly; you don't have to manually build a string that gives the information needed on the object.

如书中所述,您应该在结果中包含所有有趣的信息。 字符串。您还应该正确记录您的方法;您可以记录生成的 String 格式,但至少应该记录您的意图(格式是否可以更改,或者不可能更改)。

As stated in the book, you should include all the interesting information in the resulting String. You should also document properly your method; you may document the resulting String format or not, but you should at least document your intent (whether the format is subject to change, or not likely to change).

最后,由您(以及您公司的标准)决定是否在每个班级中覆盖它应该是您的习惯的一部分。就个人而言,我不会在每个类中覆盖 toString(),只会在最有可能被用于debuging跟踪的那些类中。

In the end, it is up to you (and your company's standards) to decide if overriding it in every class should be part of your habits or not. Personally, I don't override toString () in every classes, only in the ones which are most at risk of being used in a debuging trace.

这篇关于什么时候应该覆盖toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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