Java toString()方法

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)

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
	 */
	@Override
	public 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

  • 15
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值