Java:打印出用于调试的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5669318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:11:50  来源:igfitidea点击:

Java: Printing out an object for debugging

javajsontostringinfinitydivide-by-zero

提问by Muhd

I would like an easy way to print out a java object, or to say it another way, serialize an object as a string. I would like to see the values of all variables contained within the object, and if there are more objects (like a list or whatever) it should print out the stuff in that object as well. Basically, it would be something like JSON encoding, but JSON doesn't support infinity, and I need to see if there is infinity or NaN in one of the double or float values.

我想要一种简单的方法来打印出一个 java 对象,或者换句话说,将一个对象序列化为一个字符串。我想查看对象中包含的所有变量的值,如果有更多对象(如列表或其他),它也应该打印出该对象中的内容。基本上,它类似于 JSON 编码,但 JSON 不支持无穷大,我需要查看 double 或 float 值之一中是否存在无穷大或 NaN。

How can I do this?

我怎样才能做到这一点?

回答by Daniel DiPaolo

You could use Gsonto serialize to JSON as it now supports NaN and +/- infinity

您可以使用Gson序列化为 JSON,因为它现在支持 NaN 和 +/- 无穷大

回答by lobster1234

More often than not ToStringBuilder.reflectionToString(Object)works great. It wont work when doing Maps though.

通常ToStringBuilder.reflectionToString(Object)效果很好。但是在做地图时它不会工作。