在String类中混淆toString()实现(源代码)

Sas*_*apu -1 java tostring

java.lang.String中toString()的重写代码如下:

public String toString(){
return this;
}
Run Code Online (Sandbox Code Playgroud)

因此,打印一个String引用变量应该打印引用变量的地址(因为toString()返回'this')但不是字符串文字.为什么我错了?

例如,考虑代码

class Sample
{
String s="dummy";
System.out.println(s);//implicit call to toString()
}
Run Code Online (Sandbox Code Playgroud)

根据toString()源代码中的逻辑,应输出(变量)s的地址,输出为"哑".为什么会发生这种情况?

Krz*_*soń 5

查看System.out.println代码,它没有使用,toString但它写了一个从String中检索的char []:

public void write(String str, int off, int len) throws IOException {
    synchronized (lock) {
        char cbuf[];
        if (len <= WRITE_BUFFER_SIZE) {
            if (writeBuffer == null) {
                writeBuffer = new char[WRITE_BUFFER_SIZE];
            }
            cbuf = writeBuffer;
        } else {    // Don't permanently allocate very large buffers.
            cbuf = new char[len];
        }
        str.getChars(off, (off + len), cbuf, 0);
        write(cbuf, 0, len);
    }
}
Run Code Online (Sandbox Code Playgroud)

println上述方法之前的调用堆栈(在Writer)中:

PrintStream:

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

private void write(String s) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(s);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush && (s.indexOf('\n') >= 0))
                out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

作家:

public void write(String str) throws IOException {
    write(str, 0, str.length());
}
Run Code Online (Sandbox Code Playgroud)