Search code examples
javamavenvisual-studio-codevscode-code-runner

Show "java.lang.NoClassDefFoundError" (with Maven) when using "Code Runner"


I am using VS Code with Maven to learn Java (my javac -version is 11.0.10) under macOS Big Sur.

It is ok when I run the code in the terminal by using "RUN," which show on the list of VS Code. However, it always shows the error "Could Not Find Or Load Main Class"(actually in Chinese "找不到或無法載入主要類別 hello") and the reason "java.lang.NoClassDefFoundError: org/seifert/learnjava8/hello (wrong name: hello)".

As you can see, the .java file is just a straightforward one to show"hello world." the whole screen image here

Had anyone who uses Code Runner met this problem before? How can I resolve this?


Solution

  • The error occurs because it must be called with its fully qualified name. To be clear, the name of this class is not hello, It's org.seifert.learnjava8.hello. I create a simple maven project, so the right execution command is:

    1. Turn to the folder java: cd src\main\java
    2. Compile the .java file: javac org\seifert\learnjava8\hello.java
    3. Run the java file: java org.seifert.learnjava8.hello enter image description here

    When it comes to run the java file by Code Runner, the execution commands is

    "code-runner.executorMap":{
        "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
    }
    

    The $dir represents the direct path to current opened file, and the javac and java command doesn't include the package to be compiled together, then caused the error: enter image description here

    So the solution is turning to the settings and edit the "code-runner.executorMap":

    "code-runner.executorMap":{
            "java": "cd /users/seiferthan/.../src/main/java && javac org/seifert/learnjava8/$fileName && java org.seifert.learnjava8.$fileNameWithoutExt",
        }
    

    enter image description here