Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vs code - Expected java package name error

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.

like image 342
x.projekt Avatar asked Jan 15 '18 09:01

x.projekt


People also ask

How to fix the declared package does not match the expected package?

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.

How do I fix a package error in eclipse?

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.

Is package declaration mandatory in java?

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.

What is Com in package name 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.


3 Answers

If your files are already in the correct directory, press F1 and type in "Clean the Java Language Server Workspace"

like image 192
Jirayu S Avatar answered Sep 21 '22 17:09

Jirayu S


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" ] }

like image 25
San M Avatar answered Sep 21 '22 17:09

San M


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.

like image 20
Alexander Avatar answered Sep 20 '22 17:09

Alexander