I have a java project with the following directory structure (as required by Gradle's 'java'
plugin, assuming all defaults).
projectRootDir
- src/main/java/com/myproj/Sample.java
- build.gradle
And
// Sample.java code
package com.myproj;
public class Sample{
...
}
Opening projectRootDir
folder in VS Code shows the following package naming error in Sample.java:
The declared package "com.myproj" doesn't match the expected package "main.java.com.myproj"
How to make VS Code recognise/use the package mentioned in the code?
Note: I am using the following extensions: Language Support for Java(TM) by RedHat and Debugger for Java by Microsoft.
First, let's make sure that the package declaration and relative source file path match. If that's already the case, we can try to close and reopen the project again. Sometimes the IDE may be out of sync with the project on disk and needs to reimport the files, resolve dependencies and successfully recompile.
Go to src folder of the project and copy all the code from it to some temporary location and build the project. And now copy the actual code from temporary location to project src. And run the build again. Problem will be resolved.
It's mandatory that class files reside on the same package or directory as declared in their source file using package keyword, failure to do will result in java.
It's just a namespace definition to avoid collision of class names. The com. domain. package. Class is an established Java convention wherein the namespace is qualified with the company domain in reverse.
If your files are already in the correct directory, press F1 and type in "Clean the Java Language Server Workspace"
Project Root --> .vscode --> settings.json
changed below entry to point to my root source folder. This was set to src/pkg1. Changed to src and it started working.
{ "java.project.sourcePaths": [ "src" ] }
Because vscode
set the src folder
as the default Java Source Path
, you should change it to folder src/main/java
. Just right click the folder src/main/java
in vscode
and click the option Add Folder to Java Source Path
, then reopen the file, and the error is gone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With