java.lang.ClassNotFoundException when running in IntelliJ IDEA - java

I creating a program to work with databases and I am getting the following error when compiling in IntelliJ IDEA. Does anyone why this is happening and how I could solve it?

The error that you get occurs not on complilation, but when you try to run your application. It happens because Java was not able to find Table.class file inside db subdirectory of the project output directory (classpath).
It can happen for multiple reasons:
wrong main class selected in the run/debug configuration
Table.java is excluded from compilation (by accident or intentionally because it contained errors and you wanted to skip it while working on other code)
class not compiled because Build step is excluded from from Before launch steps in the Run/Debug configuration
project is misconfigured and there is no Source root defined for the directory containing db subdirectory
Table.java has incorrect package statement or is located/moved to a different package
project path contains a colon : on Mac/Linux or semicolon ; on Windows, it's used to separate the classpath and will render the classpath invalid. See this thread for details. Note that Finder on Mac may display colons in the path as slashes.
the jar may not execute if one of the dependent jars is digitally signed since the new artifact will include the partial signature of the dependency. See this answer for more details.
In project structure make sure you have the right Java version for compile.
there is a known bug that sometimes a Java project created from the Command Line template doesn't work because .idea/modules.xml file references invalid module file named untitled104.iml. Fix the module name manually or create a project from scratch and don't use a template.
on Windows "Beta: Use Unicode UTF-8 for worldwide language support" Region Setting is enabled. See IDEA-247837 for more details and workarounds.
When IntelliJ IDEA is configured to store module dependencies in Eclipse format source root configuration is lost due to a known bug. Configure the module to use IntelliJ IDEA format dependencies as a workaround.
In a properly configured project and with the correct run/debug configuration everything works just fine:

the jar may not execute if one of the dependent jars is digitally signed since the new artifact will include the partial signature of the dependency. See this answer for more details.
I must again emphasis the point CrazyCoder has here.
The (Oracle) JVM used to throw a SecurityException when you tried to run a Jar-File containing broken signatures. This made sense from a "What's wrong"-Point of view.
That is no longer the case. They are indeed throwing ClassNotFoundExceptions now - even if the class is right there in the file (no matter if it is in the default package/toplevel or way down in a nested package structure).

Here's what worked for me:
I deleted .ide folder, .iml file. And all other auto generated files by intelliJ then restarted my ide and I was asked if I want to make my project run with maven that's it.
Obviously I said yes :)

This is a known bug in the IntelliJ idea.
To fix this I just deleted the .iml and the .idea and restart the IDE.
It works for most of the cases
Edit: The files will be in the project directories.

In my case the default console app template works only if the project folder path does not contain underscore (_) in it. Underscore brings the error
Error: Could not find or load main class com.company.Main
Caused by: java.lang.ClassNotFoundException: com.company.Main
IntelliJ IDEA 2021.3.1 (Ultimate Edition)
Build #IU-213.6461.79, built on December 28, 2021

If you've tried everything else that others have suggested (deleting .idea folder, rebuild, etc) there's another place to check, especially if you've built an artifact jar. When you first build an artifact jar, IntelliJ adds a folder: META-INF to src directory. in it is a single file: MANIFEST.MF which has info pointing to the Main-Class for Java to find. If you've refactored your project package, unfortunately IntelliJ does not update this file with the new changes. My MANIFEST.MF has the following correct content:
Manifest-Version: 1.0
Main-Class: org.umoja4life.fatashibackend.MainKt
Where "org.umoja4life.fatashibackend" is the package name, and "MainKt" is IntelliJ's constructed name for a (pseudo) "Main Class" because fun main() has been defined in file "main.kt" in the package directory.
Newbies: btw, This will be confusing for you because there should be no actual "class Main {}" definition despite the error message stating there should be.
Before I discovered this file and after trying everyone else's suggestions, I found it quickest to just have IntelliJ start a project (with correct package name!), initialize it with a trivial main.kt having:
fun main() { println("hello world!") }
run and test that; then, I added back in all my other files, rebuilt, ran, and tested it. Apparently IntelliJ has some secret state information stored somewhere which doesn't get correctly updated if your refactor your package name for an already running project and jar.

Related

Package folder not compiling?

So I am working on a project in intelliJ idea (community edition), and I have two source folders: engine and scripts. I also have a test folder, called Test. I was having trouble earlier when I tried to refactor some parts of this hierarchy earlier, and when I went to run it I got this error message:
Error: Could not find or load main class engine.base.Launcher
Caused by: java.lang.ClassNotFoundException: engine.base.Launcher
I think I know why it wasn't able to find the main class. When I went into the out/production folder to look, the scripts folder was the only folder that had been compiled. Does anybody know what is happening here, and how I can fix it?
Make sure you have properly configured sources directories. I.e. the parent of the scripts folder must be marked as a source root. Then when you run the Application run configuration, make sure the module where your main class is located is correctly specified.
Also make sure the project is properly built (you can run Build | Rebuild Project action to make sure all the sources are up to date compiled).

cannot find or load main class when run a jar

Firstly, I know this problem is asked frequently. But My problem is different, so please be patient to see the full description.
I have utilized intellij IDEA 2018.2 to build the jar. I have ever built the jar with 2017 and it worked fine. Recently, I have used intellij to build the jar with artifact.
And the setting seems to be fine. It worked for me before. But I ran the built jar, it indicated that "the main class cannot be run or loaded".
The jar file seems normal. But I found the META-INF is different. I have some files are strange:
I find if I delete these files except MANIFEST.MF. It can work fine. I am not sure what's the difference of the settings.
I have tried the below methods:
Try to delete the .idea folder, and open the project.
Try to remove the artifact and configure a new one.
Try to modify the output path of module.
Rebuild the project or rebuild the artifact jar.
But all the methods cannot work. And I have tried to build the jar with the same settings in both MAC OS and windows OS in intellij, but the result seem to be same. Can any one provide me with some suggestions. Thank you in advance.
The *,RSA, *.SF, *.DSA are files that are created when the jarfile is signed. Apparently, the jars that you use are signed and so if you extract the contents and place them in a new jar, the signature is invalid and Java won't accept them. So you should either remove the signatures, or resign the entire jar that your artifact produces.
I have found that what is solution for this. I should not import the dependencies as a folder. I have to import them by select all the jar files instead of the folder of the jar files.

Drools 6.0.1 - Rules not getting picked from JAR

I am working on DROOLS 6.0.1 application. I have my rule files (*.drl) packaged inside a separate project which is included as a jar file as a maven dependency. When I deploy my project, KIEModule is not able to find the rules files (which are packaged inside the jar above). I am not getting an error though but rules are not getting fired.
If I manually place the rules files under classpath say WEB-INF/rules/*.drl they are detected and rules are executed.
I was under impression that KIEmodules are auto discovered from anywhere in classpath.
Any pointers are appreciated. This is general question hence I have not included the comprehensive code files.
Everything start working once I place the *.drl files in the classpath (take them outside of jar).
Thanks
Step 1 : Found the solution, the package with DLR must be declared inside your : "kmodule.xml"
Step2: you have to create enter image description here
Step3:enter image description here

Eclipse doesn't compile java files into classes

I have no idea why, but from today Eclipse doesn't compile .java files into .class. I press the "Run" button and Eclipse only tries to run the program rather then compiles it first, so i get this error all the time:
Exception in thread "main" java.lang.NoClassDefFoundError
open problems view from window -> show view -> problems, if there's any error, fix it
eclipse will reject to compile if there is any problems in your project
Close Project -> Open Project -> Clean -> Refresh
Hope it helps for someone else
This problem happens when "for some reasons" your project is corrupted and has a red icon near the project's name in Eclipse. The solution is to save the project's folder, delete the project in Eclipse, than create the project again in Eclipse coping all the previous files saved.
I ran into this problem with Eclipse Luna, for some reason the Java builder was missing from the project. Verify that in your .project file you have something like
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
You can also configure builders from Project Properties -> Builders
When I have had this exact same problem, its cause has always been the same and the solution has worked 100% of the time for me. It's caused by a missing jar file in the project's Java build path and it's indicated by a red exclamation point decoration on the project icon. To fix the problem, go to Project|Properties|Java Build Path, click on the Libraries tab and either remove or fix the path for all missing jar files. If your project is configured to rebuild automatically, it should start a build as soon as you apply your changes.
The eclipse needs to erase the output folder when building classes.
The folder is found on Project Properties -> Java Build Path -> Default Output Folder. It can differ from general output folder name found under Eclipse Preferences. If this output folder cannot be erased for some reason (for instance, on Windows, when a shell is opened on this location), the project is marked as corrupted (as Marco Micheli describes) and the classes then are not built.
You just need to make sure the output folder can be erased.
Yes I was facing this issue. Coz Eclipse cannot build the project for Build Path error. Check that your external jar files is not showing any error. Delete the Jar file which one is missing or which one is showing re color. delete that one. add a fresh one from the correct path or location. if all the error are gone. then in the project bin folder one class file will be created and then could not load main class error will be removed too.
there can be errors in your project, or other reasons like mentioned in above answers.
or you may be a fool like me
who moved the source code to other folder and not updated source path in project build properties. in this case it was not giving any error or class files too.
check that too.
goto
Project Properties -> Java Build Path -> Source
Add or Link new source folder location.
Do clean all projects ! This will erase all old class files, so eclipse is forced to generate them again.
Some times jars in the build path might be missing even though we are not using it. Since error is there, java files wont compile into classes.
Can check errors from problems view.
Either remove jars from build path or place the missing jars in the build path.
I had problem in eclipse for load module not found and no class file was getting created.
Solution: Go to Create New Project > Under JRE section Choose Use project Specific JRE.
Now Class files are created.
Please check if all the jars are there in your build path settings.
If any jar is missing this issue might come.
I had this problem, I tried the clean, the build manually, open, closing the project, deleting, and open, etc., nothing works, and after 4 hours I get a workaround what works for me.
Please, Make a RAR, ZIP, or copy from your entire project folder as a backup if it doesn't work and you mess around, OK, now:
Clean the Project. It cleaned all my class files from the output folder, but doesn't generate the class files after the clean with the building (but we already know that)
Delete the project (warning, make sure the Delete contents is not selected or your project will dissapear). For me it says something about that desynchronysation with code mix, and hibernate, blabla)
Close myEclipse
Restart your computer.
Open myEclipse
Import the project with the option "Projects from folder or Archive", not with the "existing projects into workspace" option.
Myeclipse start to build the class files, I don't know why, but works for me, I hope this helps somebody else.
Also ensure that there are no projects with fatal errors (projects with ! symbol over it) in the build path of the project which is not generating classes under the bin directory
Just restart your machine.
Its weird but it helps we had loads of problems this type in our company for unknown yet reason. Always restarting the machine helped.
It was normally encountered while trying to run Junit tests and it could not find a class even when the Run configuration was pointed to /bin.
I encountered a similar problem: previously compiled and running java files couldn't run anymore. Eclipse showed "couldn't find class xxxx". When I checked bin folder, the previous .class files were gone. That's why Eclipse couldn't run the files, NOT because of errors in files. I don't know why it can't just re-compile the file, and why the .class file gone missing in the first place.
But I found a solution:
Simply create a dummy java file in the same package (without doing anything just create), then run it. Then magically all previous .class files came back. And I can run those files as before.
Just Remove Your all Jars (Libraries) from the Build Path and refresh and add all jars and clean and build the project
This is probably a rare event but I declared a servlet with annotations and left off the "/" before the servlet mapping name. I spent over an hour chasing my tail, installing new servers, thinking I might even need to re-install my IDE and it was this simple error! Every time I tried to load any page from my Dynamic Web Project I got a 404 error. I could not even load a plain vanilla html page. There really needs to be better error logging with the IDE and Server interaction as there was zero indication of the error and my servlet was never called at the start of my web app. Hope this helps save someone else some frustration. Always name your servlet with a / slash like /myServlet never just myServlet.
I tried many different potential solutions: cleaning, rebuilding, removing, re importing, Update Maven Project and nothing. I still couldn't run my app from Eclipse. In my case the reason was that I was running Eclipse using openjdk-11 while my project was in Java 8. After I've reconfigured Eclipse to be ran from Java 8 everything started to work (in eclipse.ini).
-vm
/usr/lib/jvm/jdk1.8.0_202/bin
I'll explain my solution to this problem: "eclipse not compiling java files into class files". I'm using Eclipse version '2020-03 (4.15.0)'. I have a project that is dependent on a java project. For the dependent project, I was not able to export a jar file containing the compiles classes and resources. To be more precise, the exported jar file did not contain any class files. The output bin folder for the project is empty after doing a project build. In examining the console output when I tried to build all projects indicated that the build failed because the dependent project was missing. In looking at one of the log outputs, I saw something indicating that the build failed because some eclipse class was missing.
One of the things I tried was to do an eclipse update. Eclipse offered up the list of changes and I tried to apply them, but the update failed. I tried to update several times but they all failed. Looking more carefully at the offered up list of updates I noticed that one of the suggested update involved "deleting" Java Development Tools. That line had an warning indicating that the entire feature could not be deleted due to other dependencies and that only the non dependent features would be deleted. Doesn't that sound suspicious. Why was the update trying to delete Java Development Tools? My speculation is that something got deleted from the Java Development tool that was causing the build process to fail. The missing class I saw earlier also suspiciously sounds like it might be part of the Java Development Tools feature.
So what I did to solve the problem was to reinstall eclipse. I used the eclipse loader application to do the reinstall. (Note, I did not uninstall it first). After the reinstall, the dependent project was able to produce classes, and things once again worked as they should.
I certainly don't know how the eclipse release got into this compromised state, but in my situation the re-install of eclipse was the only way I could find to resolve the problem.
There would be the case : if you have opened project explorer in eclipse then it may not show you classes generated under /**/build/classes, in such case open Navigator view of that project and check build directory under the same project.

Main class not found, IntelliJ building a jar

I am running into problems when I try to run the jar file created in IntelliJ.
I followed the steps laid out here: How to build jars from IntelliJ properly? and searched far and wide for other people with the same problem using IntelliJ, and found no solution.
In the menu Project Structure>Artifacts section I have the package and main class name, and I have also tried specifying the 'Class path' bit using a relative and absolute path both to the source file and the .class file (which seems hidden in the IntelliJ Project display tree..), but even with all this (I also make sure to rebuild the jar every time I change something) I get the "Cannot find the main class. Program will exit." message when I try to run the jar.
In the main project folder, there is src and out.
out contains 'production' with the package tree and the class files
out also contains 'artifacts' with the jar folder and jar executable
src contains a folder of images, the META-INF and the package tree.
the first folder in the package contains the main class, so src/ravelDemo/RavelDemoMain.java
in Project Settings>Artifacts, the main class is listed as ravelDemo.RavelDemoMain
currently, the class path is out\production\RavelSequence v1.03\ravelDemo\ but this and every other class path I've specified (or left blank) doesn't seem to point to the right place. (RavelSequence v1.03 is the name of the project).
What am I doing wrong?
Basing on the discussion is the comments above it appears that IntelliJ IDEA is building the valid executable jar with the main class correctly specified in the Manifest, this jar works fine when executed with java -jar ... command from the command line using the project target JDK version on the user's machine.
The problem is that it doesn't work on double click on #sideways8 system. It may be caused by the corrupted default Java installation or wrong .jar file type association in Windows registry. This is machine specific issue as I have no problem running the shared project jar on my system by double clicking on it.
To fix this problem you can try to uninstall all the Java versions present on this machine from the Control Panel | Programs and Features, then install new JDK from scratch so that it's the only JDK on the system and .jar file type is handled by it.
I use Total Commander which has a nice feature to check/edit file associations (File | Associate With...), here is how the .jar association is displayed when I press Edit type...:
I had the same problem. Either the jar file was created with IntelliJ IDEA or other IDE. I found out the problem in my case that I had two version of java installed on my computer (java 6 & java 8).
It's a problem of misconfiguration of the system. so remove any version of java you have and install it again and the problem is solved.

Categories

Resources