IntelliJ 中的“手表”是什么以及如何使用它们?

问题描述 投票:0回答:1

当我调试应用程序时,在调试工具窗口中有一个Watches 窗口。我一遍又一遍地阅读这本手册,但找不到任何手表的实际用途。

不知何故,我认为这是一个很酷且有用的工具,但我不使用它。

有人可以解释我什么时候应该使用它并提供一些样品吗?理想情况下,描述将与具体(想象)的情况绑定,以便我更好地将其应用到我的工作中。

intellij-idea
1个回答
11
投票

此部分允许您定义表达式,您希望了解它们如何随着调试过程的每一步而演变/变化,而无需手动检查所有可用对象及其属性。让我们看以下故意抛出 NullPointerException (NPE) 的简单示例:

public class WatchSample {

    static class Student {
        public static final int CREDITS_REQUIRED_FOR_GRADUATION = 10;
        private String name;
        private Integer credits;

        public Student(String name, Integer credits) {
            this.name = name;
            this.credits = credits;
        }

        String getName() {
            return name;
        }

        public boolean hasGraduated() {
            return credits >= CREDITS_REQUIRED_FOR_GRADUATION;
        }

        public Integer getCredits() {
            return credits;
        }
    }

    public static void main(String[] args) throws Exception {
        List<Student> students = simulateReadingFromDB();

        for (Student student : students) {
            if (student.hasGraduated()) {
                System.out.println("Student [" + student.getName() + "] has graduated with [" + student.getCredits() + "] credits");
            }
        }
    }

    private static List<Student> simulateReadingFromDB() {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("S1", 15));
        students.add(new Student("S2", null)); // <- simulate some mistake
        students.add(new Student("S3", 10));
        return students;
    }
}

有时您可能想知道为什么会出现 NPE 以及需要修复什么。因此,只需设置一个断点,添加一些监视并小心地单步执行这些行即可。最终你会看到麻烦制造者:

watches

当然这是一个基本的例子,应该这样对待。在常规应用程序中,您可能会想要检查更复杂的场景和表达式,这将更有意义,例如:

if (((position > 0 && position < MAX) || (position < 0 && position > MIN) && (players(currentPlayer).isNotDead() && move.isAllowed()) && time.notUp())....
。在这种情况下,您可以评估子表达式以查看哪个子表达式返回 false


**注意**:您还可以将断点设置为有条件的,以便程序仅在发生特定事件时暂停:

© www.soinside.com 2019 - 2024. All rights reserved.