toString 的显式调用与隐式调用
当需要有关对象的一些调试信息时,我曾经使用 toString 的隐式调用,因为如果对象为 null,它不会抛出异常。
例如:
System.out.println("obj: "+obj);
而不是:
System.out.println("obj: "+obj.toString());
除了 null 情况之外还有什么区别吗?
当前一种情况不行时,后一种情况可以吗?
编辑:
在隐式调用的情况下到底做了什么?
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.
For instance:
System.out.println("obj: "+obj);
instead of:
System.out.println("obj: "+obj.toString());
Is there any difference apart from the null case?
Can the latter case work, when the former does not?
Edit:
What exactly is done, in case of the implicit call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
差别不大。 使用较短且更有效的方法。
如果您确实出于其他原因想要获取对象的字符串值,并且希望它对 null 友好,请执行以下操作:
编辑:问题已扩展,因此我将扩展我的答案。
在这两种情况下,它们都会编译为如下内容:
当您的
toString()
是隐式的时,您将在第二个附加中看到它。如果您查看 java 的源代码,您会发现
StringBuilder.append(Object)
如下所示:其中
String.valueOf
如下所示:现在,如果你自己
toString()
,绕过空检查和堆栈帧并直接在StringBuilder
中执行此操作:所以......在这两种情况下都会发生非常相似的事情。 一个人只需多做一点工作即可。
There's little difference. Use the one that's shorter and works more often.
If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this:
Edit: The question was extended, so I'll extend my answer.
In both cases, they compile to something like the following:
When your
toString()
is implicit, you'll see that in the second append.If you look at the source code to java, you'll see that
StringBuilder.append(Object)
looks like this:where
String.valueOf
looks like this:Now, if you
toString()
yourself, you bypass a null check and a stack frame and go straight to this inStringBuilder
:So...very similar things happens in both cases. One just does a little more work.
正如其他人所说 - 使用
"" + obj
方法。根据 Java 语言规范 :
"null"
new Boolean(X)
或任何toString()
调用(或等效)code>toString()
的结果为null
,则"null"
连接字符串。As others have said - use the
"" + obj
method.According to The Java Language Spec:
"null"
new Boolean(X)
or whatevertoString()
is invoked (or equivalent)toString()
isnull
, use"null"
没有什么区别,除了像你说的那样,零安全性。 总是更喜欢前者而不是后者。
No difference except, like you say, the null safety. Always prefer the former to the latter.
实际上,如果你的不变量说对象不应该为空,那也没关系。 所以这取决于你是否接受 obj 为空。
Actually, if your invariant says the object should never be null, it doesn't matter. So it depends on whether or not you accept obj to be null.
编写通用引用类型非常容易。
运行它会给出所需的输出:
It is quite easy to write a generic reference type.
Running it gives the required output: