toString的显式vs隐式调用 [英] Explicit vs implicit call of toString

查看:538
本文介绍了toString的显式vs隐式调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想要一些关于对象的调试信息时,我常常使用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.

例如:

System.out.println("obj: "+obj);

而不是:

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?

编辑:

如果是隐式调用,究竟做了什么?


What exactly is done, in case of the implicit call?

推荐答案

没有什么区别。使用较短且工作频率较高的那个。

There's little difference. Use the one that's shorter and works more often.

如果你真的想因其他原因得到一个对象的字符串值,并希望它是null友好的,那么这个:

If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this:

String s = String.valueOf(obj);

编辑:问题已延长,所以我会延长答案。

Edit: The question was extended, so I'll extend my answer.

在这两种情况下,它们都会编译成如下内容:

In both cases, they compile to something like the following:

System.out.println(new StringBuilder().append("obj: ").append(obj).toString());

当隐含 toString()时,你会在第二个附加中看到它。

When your toString() is implicit, you'll see that in the second append.

如果你看一下java的源代码,你会看到 StringBuilder.append(对象)看起来像这样:

If you look at the source code to java, you'll see that StringBuilder.append(Object) looks like this:

public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}

其中 String.valueOf 看起来像这样:

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

现在,如果你 toString()你自己,绕过空检查和堆栈框架并直接进入 StringBuilder

Now, if you toString() yourself, you bypass a null check and a stack frame and go straight to this in StringBuilder:

public StringBuilder append(String str) {
    super.append(str);
    return this;
}

所以......两种情况都会发生非常相似的事情。一个人只是做了一些工作。

So...very similar things happens in both cases. One just does a little more work.

这篇关于toString的显式vs隐式调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆