Java空指針,Java toString()方法

 2023-11-19 阅读 25 评论 0

摘要: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 toStrin

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空指針。

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:

java contains方法。 而且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);

java中類方法?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、 讓我們看一個簡單的程序,在該程序中我們將創建一個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

java compareto,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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/183179.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息