简体   繁体   English

tostring()被隐式调用……如何?

[英]tostring() is implicitly called… how?

In the following code, how is toString() is implicitly called? 在以下代码中,如何隐式调用toString()

class Payload {
    private int weight;
    public Payload (int w) {
        weight = w; 
    }
    public void setWeight(int w) {
        weight = w; 
    }
    public String toString() {
        return Integer.toString(weight); 
    }
}

public class testpayload {
    static void changePayload(Payload p) {
        p.setWeight(420);
    } 
    public static void main(String[] args) {
        Payload p = new Payload(200);
        p.setWeight(1024);
        changePayload(p);
        System.out.println("p is " + p);
    }
}

This line: 这行:

System.out.println("p is " + p);

uses string concatenation, which is specified in section 15.18.1 of the JLS, starting with: 使用在JLS的15.18.1节中指定的字符串连接,从以下开始:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time. 如果只有一个操作数表达式的类型为String,则对另一操作数执行字符串转换(第5.1.11节),以在运行时生成字符串。

Section 5.1.11 has: 5.1.11节具有:

Any type may be converted to type String by string conversion. 可以通过字符串转换将任何类型转换为String类型。

... ...

Now only reference values need to be considered: 现在只需要考虑参考值:

  • If the reference is null , it is converted to the string "null" (four ASCII characters n, u, l, l). 如果引用为null ,则将其转换为字符串"null" (四个ASCII字符n,u,l,l)。

  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; 否则,将执行转换,就好像调用了不带参数的引用对象的toString方法一样; but if the result of invoking the toString method is null , then the string "null" is used instead. 但是,如果调用toString方法的结果为null ,则使用字符串"null"代替。

You're calling "p is " + p , which effectively is compiled to 您正在调用"p is " + p ,它实际上被编译为

new StringBuffer("p is").append(p)

This code calls p.toString() within .append() as p is Object . 此代码在.append()调用p.toString() ,因为pObject

Specified by: 指定者:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html#append(java.lang.Object) http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html#append(java.lang.Object)

This is just a language feature which is available for free. 这只是一项免费的语言功能。 See Concatenating strings section: 请参阅连接字符串部分:

Such a concatenation can be a mixture of any objects. 这样的串联可以是任何对象的混合。 For each object that is not a String, its toString() method is called to convert it to a String. 对于不是String的每个对象,将调用其toString()方法将其转换为String。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM