Java toString method is a very useful method and even though you may not know it, I am sure you have used it a lot in your programs.

Java toString方法是一个非常有用的方法,即使您可能不知道它,我也可以肯定您在程序中使用了很多方法。

Java toString方法 (Java toString method)

Let’s first establish why I said earlier that you have used toString method even though you might not know it. Do you agree to use System.out.println(object); for learning and debugging purposes? I have used that a lot in my early days and still use it to debug my code (pre production). If you look at it closely, System.out is instance of PrintStream and it’s toString method is implemented like below.

首先,让我们确定为什么我之前说过即使您可能不知道toString方法,也是如此。 您是否同意使用System.out.println(object); 用于学习和调试目的? 我在早期使用了很多东西,但仍然使用它来调试我的代码(生产前)。 如果仔细观察, System.outPrintStream实例,并且它的toString方法实现如下。

public void println(Object x) {String s = String.valueOf(x);synchronized (this) {print(s);newLine();}
}

And String.valueOf() implementation is like this:

而且String.valueOf()实现是这样的:

public static String valueOf(Object obj) {return (obj == null) ? "null" : obj.toString();
}

So ultimately println() and print() functions are calling objects’ toString() method to get the string representation and then print it. So below two statements will produce same result.

因此最终, println()print()函数调用对象的toString()方法来获取字符串表示形式,然后进行打印。 因此,以下两个语句将产生相同的结果。

System.out.println(object.toString());System.out.println(object);

Now that we agree that it’s being used a lot, let’s start to explore toString method in more detail.

现在我们同意它已经被大量使用了,让我们开始更详细地研究toString方法。

Java Object toString()方法 (Java Object toString() method)

Let’s look at a simple program where we will create a java object and call it’s toString method.

让我们看一个简单的程序,在该程序中我们将创建一个Java对象并将其称为toString方法。

package com.journaldev.string;public class JavaToString {public static void main(String[] args) {Data d = new Data(10, "Java");System.out.println(d);}
}class Data {private int id;private String name;Data(int a, String b) {this.id = a;this.name = b;}
}

When I run and compile this program, I get output as com.journaldev.string.Data@7a46a697.

运行并编译该程序时,输出为com.journaldev.string.Data@7a46a697

Now two questions arise – first is where is toString() method implemented because I don’t see it in Data class? Second is what is this output that has hardly any meaningful information.

现在出现两个问题–首先是toString()方法在哪里实现,因为我在Data类中看不到它? 其次是几乎没有任何有意义的信息的输出。

We know that java supports inheritance and Object is at the top level of this hierarchy, that is where toString method is implemented. If you look at Object class toString implementation, it’s like this:

我们知道Java支持继承,并且Object在此层次结构的顶层,即toString方法的实现位置。 如果查看Object类的toString实现,则如下所示:

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

Now it’s clear why the output is having class name with @ and then some hexadecimal number.

现在很清楚为什么输出的类名带有@,然后是一个十六进制数。

Java toString()方法要点 (Java toString() method important points)

Let’s now look at the Object toString() method javadoc and see what it says.

现在让我们看一下Object toString()方法javadoc,看看它说了什么。

  1. Java toString method returns a string representation of the object.Java toString方法返回对象的字符串表示形式。
  2. The result should be a concise but informative representation that is easy for a person to read.结果应该是简洁易懂的表示形式,便于人们阅读。
  3. It is recommended that all subclasses override this method.建议所有子类都重写此方法。

Based on above recommendation, we should almost always override toString() method to return useful information about the object. So let’s change our Data class implementation and override it’s toString method.

基于以上建议,我们几乎应该始终重写toString()方法以返回有关该对象的有用信息。 因此,让我们更改Data类的实现,并覆盖它的toString方法。

package com.journaldev.string;public class JavaToString {public static void main(String[] args) {Data d = new Data(10, "Java");System.out.println(d);}
}class Data {private int id;private String name;Data(int a, String b) {this.id = a;this.name = b;}public int getId() {return id;}public String getName() {return name;}/*** Returns JSON string with id and name* Implementation can change in future, not to rely to convert object to JSON*/@Overridepublic String toString() {return "{\"id\":"+id+", \"name\":\""+name+"\"}";}
}

Now when you will run above program, output will be {"id":10, "name":"Java"}. Now this makes more sense to anybody looking at the output.

现在,当您运行上述程序时,输出将为{"id":10, "name":"Java"} 。 现在,这对于查看输出的任何人都更有意义。

重写toString()方法的要点 (Important Points for Overriding toString() method)

Let’s see some important points you should consider while overriding toString() method.

让我们看看重写toString()方法时应考虑的一些重要点。

  1. Always use @Override annotation with it, to avoid any errors or unwanted results because of typos.始终将@Override注释与其一起使用,以避免由于错别字而引起的任何错误或不良结果。
  2. Make sure to return only useful data in toString() method, your POJO class may have some sensitive information such as email id, SSN number etc. You should either mask them or avoid them altogether, otherwise they can get printed in production server logs and cause security and data privacy issues.确保仅在toString()方法中返回有用的数据,您的POJO类可能包含一些敏感信息,例如电子邮件ID,SSN编号等。您应该屏蔽它们或完全避免使用它们,否则它们将被打印在生产服务器日志和导致安全和数据隐私问题。
  3. It’s always a good idea to provide some documentation regarding the output of toString() method. For example, someone should not use my toString() implementation to convert object to JSON string. That’s why I have explicitly added that implementation can change in future.提供一些有关toString()方法输出的文档始终是一个好主意。 例如,某人不应使用我的toString()实现将对象转换为JSON字符串。 这就是为什么我明确添加了实现可以在将来更改的原因。
  4. You should always provide getter methods for the object attributes that are part of toString() method output string. Otherwise a programmer would be forced to parse toString() output to get the desired data because there is no other choice.您应该始终为对象属性提供getter方法,这些对象属性是toString()方法输出字符串的一部分。 否则,由于没有其他选择,程序员将被迫解析toString()输出以获得所需的数据。
  5. It’s always best to provide implementation of toString() method, even though you might think that it’s not required. Think of below code where someone is printing a list of data objects.
    List<Data> list = new ArrayList<>();
    list.add(new Data(10, "Java")); list.add(new Data(20, "Python"));
    System.out.println(list);

    Which output you would prefer?

    Without toString() implementation:

    With toString() implementation:

    [{"id":10, "name":"Java"}, {"id":20, "name":"Python"}]

    始终最好提供toString()方法的实现,即使您可能认为它不是必需的。 考虑下面的代码,其中有人在打印数据对象列表。

    您需要哪种输出?

    没有toString()实现

    [com.journaldev.string.Data@7a46a697, com.journaldev.string.Data@5f205aa]

    使用toString()实现

That’s all for brief roundup on java toString() method.

这就是对java toString()方法的简短总结。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/18578/java-tostring-method

Java toString()方法相关推荐

  1. JAVA toString方法详解

    JAVA toString方法 在Java中,我们经常会编写许多自定义类.在使用时,我们如何打印出这些类中实例变量? class value {private int s;public void se ...

  2. java 自定义tostring_自定义java toString方法

    java里我们经常System.out.println(xx) xx可以是一个List 一个HashMap 一个HashSet 一个什么奇怪的自定义的类. 只要能正确显示字符串的背后起作用的都是一个叫 ...

  3. java tostring方法_Java程序员小伙启动项目报错,原来是使用了lombok

    每一个程序员在进公司的第一天,可能是在搭建环境,启动项目.小伙在启动 SpringBoot 项目中发现:代码中缺失大量的 getter/setter ,一查原来使用 lombok . 首先,解决项目中 ...

  4. [Java基础][Java]toString()方法

    [原理解析] toString()方法返回反映这个对象的字符串 因为toString方法是Object里面已经有了的方法,而所有类都是继承Object,所以"所有对象都有这个方法" ...

  5. java tostring方法_Java虚拟机如执行方法调用的(二)?

    虚方法调用 Java里所有非私有实例方法调用都会被编译成invokevirtual指令. 接口方法调用都会被编译成invokeinterface指令.这两种指令都属于Java虚方法的调用. 在大多数情 ...

  6. Java toString()方法的要点

    Java toString要点 一.关于Object类中的tostring()方法 1. toString源代码长什么样? public String toString(){return getCla ...

  7. java如何重写onestring,44 java toString 方法 重写equals 方法

    package com.wjl.zy131227; /** * 打印对象 * toString 方法 * @author Administrator * */ public class ToStrin ...

  8. java重写的代码_java tostring方法重写代码示例

    当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toString()方法 默认情况下 System.out.printl ...

  9. java中Object类的hashCode和equals及toString方法。

    java中的hashcode.equals和toString方法都是基类Object的方法. 首先说说toString方法,简单的总结了下API说明就是:返回该对象的字符串表示,信息应该是简明但易于读 ...

最新文章

  1. Scala微服务架构 三
  2. python划分代码_多分类评价指标python代码
  3. python叫什么-又一个python小游戏,叫什么不知道了。。。
  4. 假日教程-ZStack映像檔系列(TurnkeyLinux Observium)
  5. 干货|各种WAF绕过手法学习
  6. 使用DataGridView数据窗口控件,构建用户快速输入体验
  7. 百度UEditor编辑器使用(二)
  8. fft matlab 区别,Matlab中fft与fwelch有什么区别?如何用fft求功率谱?
  9. 各种存储分配算法java代码实现_Java实现操作系统中四种动态内存分配算法:BF+NF+WF+FF...
  10. 零基础学python全彩版-零基础轻松学Python:青少年趣味编程(全彩版)
  11. Mysql的key_len计算方法
  12. python使用scrapy爬取百度地图POI数据
  13. Sqlserver2008数据库可疑文件
  14. krpano点击场景获取点击位置的场景坐标
  15. 武汉大学计算机考研复试考什么,2018武汉大学计算机考研复试经验贴
  16. Java连rabbitMQ 报错 An unexpected connection driver error occured
  17. 考研英语单词-近义词分类-Fourth Day
  18. Error与Exception的异常定义以及简介(简单理解介绍是为了下一节的异常处理与捕捉)
  19. mysql 1356错误_MySQL ERROR 1356 (HY000)
  20. 服务器绑定自己的域名-腾讯云

热门文章

  1. 使用jquery实现局部刷新DIV
  2. Oracle 数据文件 实际使用量 计算说明
  3. 使用特殊字体实现特殊报表效果
  4. 操作 SQL Server Mobile 2005 数据库的常用 C# 代码 (转自黎波)
  5. [转载] C++ std::vector指定位置插入
  6. [转载] python中set函数是什么数据类型_Python基本数据类型-list-tuple-dict-set详解
  7. 机器学习-数据科学库-day5
  8. QT最常用的字符串操作
  9. 算法总结之 在数组中找到一个局部最小的位置
  10. bzoj 1015 [JSOI2008]星球大战starwar