首页 > 解决方案 > toString method in Java benefits

问题描述

What is the benefit in using toString method in java if it has always need to be overridden?

Example:

String var = "3";
byte [] var_inBytes = var.getBytes();
String var2 = var_inBytes.toString(); 

this will give me the name of the object followed by the hash code okay then when we can use toSting method without overriding?

标签: javastringobjectoverridingtostring

解决方案


toString()方法是程序员最好的朋友之一。我至少在每个业务对象或每个实体上使用它来列出它们的可变成员内容。

当发生意外问题并且您遇到大麻烦时,特别是在您遇到紧急情况时,如果您可以阅读:“项目{Id:125,名称:Smith,地址:15的大麻烦King Square} ”,而不是“一件物品上的大麻烦”。
您不仅拥有可用于内部研究的 id,还可以告诉最终用户谁真正受到影响:史密斯先生。可能你的最终用户会有一个线索:“哦,是的,我们正在对他进行特殊操作,因为......

在大量日志中,当然只是在TRACEDEBUG级别上,我以这种方式转储了许多业务对象或实体内容。如果发生了一个非常大的问题,即使在生产中,并且它是可重现的,我可能(在可怕的情况下)以TRACE模式重新启动应用程序并了解实际发生的情况。

toString()是一个生命的救星,我说。


推荐阅读