IDEA Debug 时对象莫名其妙被修改了

IDEA Debug About 1,714 words

现象

IDEA在开启Debug运行时,点击查看对象,对象中的字段的值每次都会变化。

原因

对象复写了toString()方法,IDEA在我们点击查看对象信息时,会默认调用toString()方法,帮助我们直观的查看对象信息。

代码

复写了toString()方法。

static class Person {
    public String name;

    public int age;

    public AtomicInteger hair = new AtomicInteger(100);

    @Override
    public String toString() {
        return name + "-" + age + "-" + hair.getAndDecrement();
    }
}

解决

在设置中关闭默认调用toString()方法。设置路径如下:

取消勾选:Enable 'toString()' object viewEnable alternative view for Collections classes两个选项。

File | Settings | Build, Execution, Deployment | Debugger | Data Views | Java

典型案例

ConcurrentLinkedQueue中复写了toString(),在多线程Debug时如果去查看节点Node会出现问题。

public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> implements Queue<E>, java.io.Serializable {

    public String toString() {
        String[] a = null;
        restartFromHead: for (;;) {
            int charLength = 0;
            int size = 0;
            for (Node<E> p = first(); p != null;) {
                final E item;
                if ((item = p.item) != null) {
                    if (a == null)
                        a = new String[4];
                    else if (size == a.length)
                        a = Arrays.copyOf(a, 2 * size);
                    String s = item.toString();
                    a[size++] = s;
                    charLength += s.length();
                }
                if (p == (p = p.next))
                    continue restartFromHead;
            }

            if (size == 0)
                return "[]";

            return Helpers.toString(a, size, charLength);
        }
    }

}

视频讲解

https://www.bilibili.com/video/BV1mB4y1V7fy

https://www.ixigua.com/i7135448256280330793

Views: 1,466 · Posted: 2022-08-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh