Could not find or load main class in vs code - java

The case:
I have created a complex java project (spring boot) with maven build in IntelliJ and I was able to run it, everything was working fine. Now, as IntelliJ hasn't a community edition with spring boot, I had to move to vs code. I didn't change anything in my project, I just opened the folder (which contains the pom.xml and the src folder) in vs code and let vs code load the java project (earlier I installed all the extensions like spring boot, java, etc. for vs code).
After vs code opened the project successfully, I wanted to run it in the main method by clicking the run text (I inserted the image, that you can see the folder structure):
But as stated above, I get the famous error. I reloaded the window, I cleared the workspace, I set the JAVA_HOME and CLASSPATH variables in the env variables and tried, tried, tried it again, but no success. What the hell can I do on top of that? It worked in IntelliJ, it should work in vs code too. I use java se17. Note, that if I start a new simple project, the program get's compiled and executed without any error.
Another curiosity is, if I try to load the maven dependencies, vs code says, that it can't create the dependency tree, but if I run the mvn dependency:tree command, I get all the dependencies and it says, that the build was successful.
What is going on here?
EDIT: my antivirus program blocked maven, so, the problem with the dependency tree is now gone, but the error with the classpath remains.

Related

How to save Java Project from IntelliJ IDEA to Git repo so it will build on another PC after cloning?

I'm building a simple calculator app from a tutorial/class on Pluralsight (Java Fundamentals class), which starts with a Main.java file, and adds a class file later, MathEquation.java.
I created a Git repo to track my progress, and uploaded to Github: JavaFundamentalsClass. I used GitIgnore.IO to find a Java IntelliJ .gitignore file, and everything seemed to be working fine on the original PC I was using.
However, after switching over to a different PC, with a fresh install of IDEA, I cloned down the repo from Github, and found that the project would not build and/or run. I get this error:
"C:\Program Files\RedHat\java-1.8.0-openjdk-1.8.0.191-1\bin\java.exe" -Dfile.encoding=windows-1252 -jar ""
Error: Unable to access jarfile
Process finished with exit code 1
I suspect that there is something in the .gitigore file that is keeping some of the project, dependency, or build information from being saved in the repo that keeps IDEA from having all the info it needs to build and run the Main.java correctly.
Can anyone help? You should be able to download the project from the repo linked above in it's currently broken state, including the .gitignore file.
Additional Info
I wiped my repo clean and recloned and I forgot, originally it doesn't even give me the run button (it is grayed out). I had to do a procedure with "Add Configuration" from a search I did for that to show up to get the error above.
Also, I did install java from the OpenJDK, rather than oracle. I figured with Oracle cutting off commercial development maybe start the switch now as I'm learning, but maybe that's the issue (normal Java on my other PC).
It's working, but...
First thing - Intellij needs to know where Java is. It appears that if the SDK/JDK is not installed prior to Intellij, you will need to tell it where Java is after installing. Or if you use OpenJDK instead of Oracle Java SDK. You can do that at View/Open Library Settings, under Platform Settings / SDKs (select the JDK home path).
Then, after setting up Java, I am able to get everything working in Intellij IDEA if I find the Main.java file, right-click, and choose "Run main.main()". This runs the program okay, and also creates a Main configuration in the Run/Debug configuration area, and finally the "Run" button becomes available.
So I can get it working, but if I wipe all the files and clone it fresh from the remote repo, I have to go through running the Main.java file directly again to recreate the configuration.
So, this still doesn't answer my original question. Why doesn't this configuration get saved in the repo? What file is this information saved in? Is there something in the .gitignore file that is keeping this information from being saved to the repo?
Look like you have a different java version on your second machine.
First of all, check your java version
Update the configuration of your project, right now it pointing to java 1.8
https://github.com/LightCC/JavaFundamentalsClass/blob/master/.idea/misc.xml
I think it might be because of java not installed on the other PC you were trying. If it is installed just check whether the path mentioned has java executable file.
The first part is ensuring Java is setup, and that Intellij IDEA knows where Java is, per the other answers, comments, and addendums to the question.
The second part is setting up the run/debug configuration, per the "It's working but.." section of the question. This can be created automatically by right-clicking the file that has the main class to be run (usually Main()...), and selecting the "Run Main.main()" option (replacing Main and main() with the file and function which needs to be run)
The final piece is that to get the run/debug configurations to save to the repo, you either need to:
Share the workspace.xml file (i.e. make sure this is not in the .gitignore file). However, there is a lot of user-specific stuff in that file, so it should normally be excluded from the repo.
Or, edit the configuration and checkmark the "Share" box in the upper right-hand corner (just right of the "Name" field). This will put the configuration into a separate folder inside the .idea folder, which should not be excluded from the repo by .gitignore.

Eclipse will only run a non-existing project

I'm trying to have Eclipse run my project called ScrapeMax.
Whenever I try to run this project, instead Eclipse will run a project called Wiki Expander. Wiki Expander does not exist within the workspace and is not imported in Eclipse.
The following does not solve the problem:
Main is ofcourse included in the class.
Main is not capitalised.
Main is ofcourse public.
Choosing "Runs As/Java Application" runs Wiki Expander instead of ScrapeMax.
The main-class is called Startup, and the file is called Startup.java.
I've tried deleting all Run configurations and recreating it for ScrapeMax. It doesn't help.
The Run configuration does ofcourse involve the proper main class.
Cleaning all projects didn't solve it.
/eclipse -clean didn't solve it.
Removing the project and importing it again didn't solve it.
How do I make Eclipse stop running Wiki Expander, og run ScrapeMax like I want it to?
seems like eclipse cached wiki project,You need to clean up your eclipse cache.check out here that how to clean eclipse cache

Command works in terminal but not with java [duplicate]

What are the possible causes of a "java.lang.Error: Unresolved compilation problem"?
Additional information:
I have seen this after copying a set of updated JAR files from a build on top of the existing JARs and restarting the application. The JARs are built using a Maven build process.
I would expect to see LinkageErrors or ClassNotFound errors if interfaces changed. The above error hints at some lower level problem.
A clean rebuild and redeployment fixed the problem. Could this error indicate a corrupted JAR?
(rewritten 2015-07-28)
Summary: Eclipse had compiled some or all of the classes, and its compiler is more tolerant of errors.
Long explanation:
The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn command, this may happen.
The cure is to fix the errors and recompile, before running again.
The setting is marked with a red box in this screendump:
try to clean the eclipse project
you just try to clean maven by command
mvn clean
and after that following command
mvn eclipse:clean eclipse:eclipse
and rebuild your project....
Your compiled classes may need to be recompiled from the source with the new jars.
Try running "mvn clean" and then rebuild
The major part is correctly answered by Thorbjørn Ravn Andersen.
This answer tries to shed light on the remaining question: how could the class file with errors end up in the jar?
Each build (Maven & javac or Eclipse) signals in its specific way when it hits a compile error, and will refuse to create a Jar file from it (or at least prominently alert you). The most likely cause for silently getting class files with errors into a jar is by concurrent operation of Maven and Eclipse.
If you have Eclipse open while running a mvn build, you should disable Project > Build Automatically until mvn completes.
EDIT:
Let's try to split the riddle into three parts:
(1) What is the meaning of "java.lang.Error: Unresolved compilation
problem"
This has been explained by Thorbjørn Ravn Andersen. There is no doubt that Eclipse found an error at compile time.
(2) How can an eclipse-compiled class file end up in jar file created
by maven (assuming maven is not configured to used ecj for
compilation)?
This could happen either by invoking Maven with no or incomplete cleaning. Or, an automatic Eclipse build could react to changes in the filesystem (done by Maven) and re-compile a class, before Maven proceeds to collect class files into the jar (this is what I meant by "concurrent operation" in my original answer).
(3) How come there is a compile error, but mvn clean succeeds?
Again several possibilities: (a) compilers don't agree whether or not the source code is legal, or (b) Eclipse compiles with broken settings like incomplete classpath, wrong Java compliance etc. Either way a sequence of refresh and clean build in Eclipse should surface the problem.
I had this error when I used a launch configuration that had an invalid classpath. In my case, I had a project that initially used Maven and thus a launch configuration had a Maven classpath element in it. I had later changed the project to use Gradle and removed the Maven classpath from the project's classpath, but the launch configuration still used it. I got this error trying to run it. Cleaning and rebuilding the project did not resolve this error. Instead, edit the launch configuration, remove the project classpath element, then add the project back to the User Entries in the classpath.
I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.
Just try to include package name in eclipse in case if you forgot it
Import all packages before using it, EX: import java.util.Scanner before using Scanner class.
These improvements might work and it will not give Java: Unresolved compilation problem anymore.
Also make sure to check compiler compliance level and selected jdk version is same
As a weird case, I encountered such an exception where the exception message (unresolved compilation bla bla) was hardcoded inside of generated class' itself. Decompiling the class revealed this.
I had the same issue using the visual studio Code. The root cause was backup java file was left in the same directory.
Removed the backup java file
When the build failed, selected the Fix it, it cleaned up the cache and restarted the workSpace.

finding changes eclipse makes to maven project

I have a maven project which I have downloaded from this link. When I make a couple changes to it, it runs perfectly from the command line when I type:
mvn clean install tomcat7:run-war -Dmaven.test.skip=true
in the directory to which the zip was extracted. (The only 2 changes required to make it work on the command line are to 1.) add a plugin tag for tomcat 7 in pom.xml and 2.) create a context.xml file in the webapp/META-INF folder. Everything else in the app remains the same as the github verion, and the app runs fine from the command line using the command given above and then typing the url in the browser.)
However, when I import the project into eclipse as an existing maven project, and then try to run the app, the app starts throwing errors related to not finding a couple of jars which are clearly in the repository. The app no longer compiles from the command line, or from eclipse. I even tried to run the app as a maven build from eclipse and even changed the maven instance eclipse uses to the freestanding maven that works from the command line instead of the embedded maven in eclipse, but the app still threw the same errors when I tried to run it.
But then, when I repeated the steps with a fresh copy of the app, the fresh copy runs fine from the command line, while the copy that eclipse touched does not compile by any method.
It seems that eclipse has made some changes to the app in the process of importing it as an existing maven project into eclipse. How can I locate the specific changes that eclipse has made to the app? I would like to be able to use eclipse as my IDE, but I cannot do so unless it can compile the code.
This answer was originally posted as a comment it turns out that resolved the OP's problem, and as He asked I'm turning into an answer.
First set your eclipse to use the JDK instead of the JRE. Just as a reference this configuration on Eclipse is Normally on Window->Preferences...->Java->Installed JREs:
Second (as you already did) change eclipse maven to look at installed maven that runs on the command line again.
I've encountered some problems with maven running with the JRE instead of the JDK. Try it and let me know. I will sleep now. Tomorrow I will see what happened.

Eclipse - java.lang.ClassNotFoundException

When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.
My project structure is the following:
parent project (pom-packaging)
Web project (war-packaging - my JUnit-test is in here)
Flex project
Configuration project
edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.
Here's my JUnit's run-configuration:
alt text http://www.walkner.biz/_temp/runconfig.png
Testclass (but as I said; it doesn't work with a simple HelloWorld either...):
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;
public class UserDaoTest {
/**
* the applicationcontext.
*/
private ApplicationContext ctx = null;
/**
* the user itself.
*/
private User record = null;
/**
* Interface for the user.
*/
private UserRepository dao = null;
#Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}
#After
public void tearDown() throws Exception {
dao = null;
}
#Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}
#Test
public final void testIsNoUser() throws Exception {
Assert.assertFalse(dao.isUser("not", "existing"));
Assert.assertFalse(dao.isUser(null, null));
Assert.assertFalse(dao.isUser("", ""));
}
}
I've come across that situation several times and, after a lot of attempts, I found the solution.
Check your project build-path and enable specific output folders for each folder. Go one by one though each source-folder of your project and set the output folder that maven would use.
For example, your web project's src/main/java should have target/classes under the web project, test classes should have target/test-classes also under the web project and so.
Using this configuration will allow you to execute unit tests in eclipse.
Just one more advice, if your web project's tests require some configuration files that are under the resources, be sure to include that folder as a source folder and to make the proper build-path configuration.
Carlos approach helped!
Eclipse - java.lang.ClassNotFoundException
Try to check the classpath of the junit run configuration:
Open your run configurations
Click on the jUnit-Test you want to start
go to the classpath tab
Try to add a folder (click on user entries, click on advanced, click on add folders, click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source))
works for me.
your build classpath is correct, which is why you can compile. the classpath for your JUnit needs to be checked. go to the Run menu and choose 'open run dialog.' in there you should see a tree on the left with JUnit as an option. open that node and find and select your test. on the right pane you will see a tab for classpath. take a look to ensure that your class that the test is trying to instantiate would be found.
edit:
this seems to be an issue with maven and its behavior after a release changed the default Eclipse output folders. i have seen solutions described where
placing maven into the bootclasspath ABOVE the jre works, or
running mvn clean test does the trick or
refreshing all of your eclipse projects, causing a rebuild fixes the problem
going to your project and selecting Maven->Update Configuration solve the problem
with the first three, there were reports of the issue recurring. the last looks best to me, but if it doesnt work, please try the others.
here and here is some info
Enabling [x] Use temporary JAR to specify classpath (to avoid classpath length limitations) inside the Classpath tab of the Run configuration did the trick for me.
If your project is huge and you have lots of dependencies from other sibling projects and maven dependencies, you might hit the classpath length limitations and this seems to be the only solution (apart from making the directory to you local maven repo shorter (ours already starts at c:/m2)
The problem might be missing the class file in your build folder. One solution is clean the project and rebuild it.
There are many convoluted suggestions here.
I've encountered this problem multiple times with Maven projects after moving resources around by drag 'n' drop, or performing refactoring of class names.
If this occurs, simply copy (not move) the problem Test Case (.java) via terminal/file browser to another location, right-click -> Delete in Eclipse and choose to delete on disk when given the option, move/copy the copied file to the original file location, then select your project in Eclipse and press F5 to refresh resources.
This is quick and easy to do, and has fixed the problem permanently for me every time.
This was my solution to the problem. Of course, many things can cause it to occur. For me it was that Maven2 (not the plugin for Eclipse) was setting the eclipse profile up to use a different builder (aspectJ) but I did not have the plugin in eclipse./
http://rbtech.blogspot.com/2009/09/eclipse-galileo-javalangclassnotfoundex.html
Cheers
Ramon Buckland
Sachin's right:
Even with correct class path, the problems tab will show that some dependency or the Resource/project has error that needs to be fixed in order for maven to automatically build and create classes when you create or make a change in your test class.
"Hi,
Its very Old Jul (which year) but I had the same problem .
Actual issue found that eclipse was not able to generate class file for the java file , classpath was proper.
See the problem tab and check if your project is missing something/file. you can create a new proj and add files one by one and build them until it stops compiling and creating classes ( check the workspace/proj/bin/package/ folder for classes )
its wierd but true , ecplise was failing in compliation because 4 of 20 java files were using a single image which was missing. and as result none of the java file was compiled .
CLASSPATH is not a issue here."
We had the exact exception (using SpringSource Tools, tomcat, on Win7) and the cause was that we had refactored a filename (renamed a file) from SubDomain.java to Subdomain.java (D vs d) and somehow it collided though SpringSource was showing the new name Subdomain.java. The solution was to delete the file (via SpringSource) and create it again under the name Subdomain.java and copy-pasting its former content. Simple as that.
I had the exact same problem but I figured it out! Go to your project file and right click on it, then click Refresh or hit F5. Then try and run it. If it still doesn't work then just forget it, as I had the EXACT same problem and it just means you version of Eclipse is garbage.
JUnit test from inside eclipse gave me also NoClassDefFoundError.
Running 'mvn clean test' from command line gave me following error on several jars:
invalid LOC header (bad signature)
Deleting these jars from local m2 repository and running 'mvn clean test' again
solved my problem.
click on project->properties->Java build path->Source and check each src folder is still valid exist or recently removed. Correct any missing path or incorrect path and rebuild and run the test. It will fix the problem.
All I did was Properties -> Java Build Path -> Order and Export -> Enabled all unchecked boxes -> moved Junit all the way up
Tried
Link : [here][1]
Open your run configurations
Click on the jUnit-Test you want to start
go to the classpath tab
Try to add a folder (click on user entries, click on advanced, click on add folders,click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source))
worked after
Maven 2 LifeCycle >> test
I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh. Nothing worked. What did work was copying the class to a new name which runs fine -- bizarre but true.
After putting up with this for some time, I just fixed it by:
Via the Run menu
Select Run Configurations
Choose the run configuration that is associated with your unit test.
Removing the entry from the Run Configuration by pressing delete or clicking the red X.
Something must have been screwed up with the cached run configuration.
I had the same problem. All what I did was,
i). Generated Eclipse artifacts
mvn clean eclipse:eclipse
ii). Refresh the project and rerun your junit test. Should work fine.
while running web applications Most of us will get this Exception. When you got this error you have place .class files in proper folder.
In web applications all .class files should sit in WEB-INF\Classes folder.
if you are running web app in Eclipse please follow the steps
Step 1: Right click on Project folder and Select Properties
Step 2: Click on "Java Build Path" you will see different tabs like "source" , "projects", "libraries" etc
Step 3: select Source folder. under this you will see your project details
Step 4: in the "Source" folder you will see Default Output Folder option. here you have to give the classes folder under WEB-INF.
just give the path like projectname/WebContent/WEB-INF/classes
the structure depends on your application
please do remember here you no need to create "classes" folder. Eclipse will create it for you.
Step 5: click on "OK" and do the project clean and Build. that's it your app will run now.
I solve that Bulit path--->libraries--->add library--->Junit check junit4
Usually this problem occurs while running java application java tool unable to find the class file.
Mostly in maven project we see this issue because Eclipse-Maven sync issue. To solve this problem :Maven->Update Configuration
I suggest trying adding this to the VM arguments;
-verbose:class -verbose:module -Xdiag
Then you can debug it from Eclipse which should print out some message like;
java.lang.ClassNotFoundException: org.adligo.somewhere.Foo
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at java.base/sun.launcher.LauncherHelper.loadMainClass(LauncherHelper.java:760)
at java.base/sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:655)
From this you can set a breakpoint on LancherHelper.java 760 to debug the Eclipse Lanucher itself. In my case I noticed that user classpath appeared to be null, even though I have many jars in it in the Lanuch config.
Make sure if your test class working before , but you facing issue all of sudden. then clean your project and build it again. Make sure project has been configured in build path as read above article.
Well, you can solve this problem basically by creating a new project.
Close the project (save the code in another folder on your computer).
Create a new project (add a new final directory and do not leave the default directory selected).
Remake your previous project adding the code saved before.
This happens because probably you created a project and didn't select a directory/folder or something like that.
I hope had helped you!
Please point to correct JDK from Windows > Preferences > Java > Installed JRE.
Do not point to jre, point to a proper JDK. I pointed to JDK 1.6U29 and refreshed the project.
Hereafter, the issue is gone and jUnit Tests are working fine.
Thanks,
-Tapas
I've run into a same error in Eclipse recently, i.e., the Eclipse IDE couldn't find the Unit test class no matter how I change the configurations. Learning from the previous posts here and in other web sites, I've double checked and triple checked the classpath and source info, and move up and down the source folder and libraries, in both the "Run Configuration" and the "Java Build Path" config windows, and I've also cleaned the Project and rebuilt it, but none of the tricks work for me. The specific Java project is an old ANT compiled project and have lots of jars included in Eclipse library.
Then, I changed the unit test class to add a main() method and right click it to "Run As" a Java Application instead of JUnit test, and suddenly, Eclipse seems to wake up and identified the class correctly. Afterwards, I switched it back to a Unit test application, and it is still working.
This seems to be a bug in Eclipse, I am guessing the large number of libraries (>260) may confused the JVM's ability to locate my JUnit class.
I was hit with this issue also and was able to come up with a sufficient solution for my case. If your Eclipse project has a .classpath file in your project root (see it in Navigator view instead of Package Explorer view), be sure that your Maven classpathentry appears prior to your JRE Container classpathentry.
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>
If your project does not have a .classpath file, you can edit your project's Java Build Path to switch the Order and Export. If your project has the .classpath file and you only change your ordering in the Java Build Path, you will see that the ordering is not impacted and the issue will continue to occur.
And a project->clean never hurts things after you make the change.
Make sure your test launch configuration does NOT contain the following lines, OR try enabling automated Maven dependency management.
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.maven.ide.eclipse.launchconfig.classpathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.maven.ide.eclipse.launchconfig.sourcepathProvider"/>
I tried everything I read in this long post and, incredibly, what worked for me was, rather than clicking on the test class and selecting Run as JUnit test, clicking on the test method and running as JUnit test. I have no idea why?
Deleting the project from eclipse (Not from hard disk) which in a way is cleaning the workspace and reimporting the project into eclipse again worked for me.
Changing the order of classpath artifacts in the Java Build Path resolved it for me.
Right Click on the project and go to Project Build path.
Go to, Order and Export tab and move the JRE system library to after the sources.
This should fix it.
JUnit 4.4 is not supported by the JMockit/JUnit integration. Only
versions 4.5 or newer are supported that.

Categories

Resources