Issue
I am using VSCode 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 VSCode. 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:
- Turn to the folder java:
cd src\main\java
- Compile the .java file:
javac org\seifert\learnjava8\hello.java
- Run the java file:
java org.seifert.learnjava8.hello
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:
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",
}
Answered By - Molly Wang-MSFT
Answer Checked By - Willingham (JavaFixing Volunteer)