为什么即使从未调用代码块也会出现方法丢失错误?

Why is there a missing method error even when the code block is never called?

我正在编写 Mad Libs 程序。在里面,有各种各样的故事……或者至少会有。目前,只有一个。但是我选择故事的方法参考了我还没有做过的方法。出于某种原因,这段代码不会编译,即使我在任何时候都没有调用未创建的方法。这是为什么?

这是选择故事的方法。

public void chooseStory (int choice)
    {
        switch (choice)
        {
        case 1:
            story1();
            break;
        case 2:
            story2();
            break;
        case 3:
            story3();
            break;
        case 4:
            story4();
            break;
        }

但即使 choice 为 1,我仍然得到错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method story2() is undefined for the type MLServer
    The method story3() is undefined for the type MLServer
    The method story4() is undefined for the type MLServer

    at MLServer.chooseStory(MLServer.java:13)
    at MLApp.main(MLApp.java:31)

为什么 JVM 正在评估从未命中的代码?

Java不知道会调用什么代码。例如,您也可以从服务器上传和使用 class 文件。除此之外,预测代码的哪些部分将被访问而哪些不被访问将是相当复杂的(如果涉及用户选择,甚至是不可能的)。并且生成的字节码将包含对甚至不存在的代码的引用,这将使编译和执行变得非常复杂。