Eclipse can't find / load main class - java

My Eclipse (Indigo) was running just fine. I created a simple class Hello. It is placed in package cont in the folder ch13. However, when I try to run it from Eclipse I get info from Java Virtual Machine Launcher:
Could not find the main class: cont.Hello.
I tried to run other classes from this package and they run just fine (that is the classes that existed there before). However any new class I create in this package has these problems. Actually any new class I create in Eclipse runs into this problems. I decided to check how it works from the command line. It seems that the problem still exist - I get same error. I checked the path and it is C:\Program Files\Java\jdk1.7.0_02\bin, which is correct (note the other classes are running from Eclipse just fine). I tried to run with java -cp . Hello and there are some Errors produced starting with java.lang.NoClassDefFoundError: Hello (wrong name: cont/Hello). Code itself is simple:
package cont;
public class Hello {
public static void main(String[] args){
System.out.println("Hello");
}
}
How can I fix it so that my classes still run under Eclipse?

.metadata is corrupted.
Steps:
Warning: Deleting .metadata will delete all your Eclipse configurations, plugins, project setups. Make a backup before you attempt this!
Stop eclipse, delete .metadata in workspace and restart eclipse
Import Project
Run again

Removing the Run Configuration
Sometimes I have a similar problems in some pre-release versions of eclipse. For fix the error, I delete the Run Configuration. You can find that in menu Run, Run Configurations...
Then I launch the app with Alt+Shift+X, then J. If this don't work, Ctrl+F11.
Deleting the .metadata directory
In another way, the configuration settings for your current workspace may are corrupted. Those settings are in the .metadata directory in your current workspace 1. In that case, there is no other choice than delete the directory:
Close eclipse.
Delete the .metadata directory.
Start eclipse.
Import the projects.
Run the project again.
Notes
You will see that directory with File > Switch Workspace > Other...

I have solved the issue following way:
Go to Run Configuration (Right Click on Java File->Run->Run Configuration).
Go to ClassPath Tab:
Click on Advanced -> Add Folders -> Add bin directory (which has class file in it for Java source code)
Re run the code, now it will solve the issue. It worked for me

Note: This worked in the past and I received many up votes. Perhaps this is not a solution anymore - but it once was - as the eclipse version was indicated.
Problem
This can also be caused by a Java Build Path Problem.
In my case, I had a an error:
A cycle was detected in the build path of project {project}. The cycle consists of projects {x, y, z}.
This can occur when you include other projects in the build path of the project you wish to run. In fact, all the projects will fail to run with the error
Could not find the main class: Example.class
Solution
Open
Windows -> Preferences -> Java-> Compiler -> Building -> Build Path Problems
Uncheck the Abort build when build path errors occur toggle
This seems like a can of worms if you end up with other build path errors I image. So use with caution.
Note: This only works if you have a "cycle error". This error message can be found in the "Markers" tab
I found the solution to this here
Info
Java 1.8.0_152
Eclipse Photon (June 2018)

Renaming the main class should be enough (and easiest):
- Go to your class and set cursor to your class name;
- ALT + Shift + R and rename the class (build if not done automatically);
- You should be able to run it now;
- Rename the class to the old name if you want;

You must have main function in your class. Like
public class MyDataBase {
public static void main(String args[]) {
}
}

I had this same problem in a Maven project. After creating the src/test/java folder within the project the error went away.

Another tip: I initialized static fields in a wrong order - surprisingly it didn't bring up a Problem (NullPointerException?), instead Eclipse complained with exactly the message OP posted. Correcting the static initialization order made the class run-able. Example:
private static ScriptEngineManager factory = null;
private static ScriptEngine engine = null;
static {
engine = factory.getEngineByName("JavaScript");
// factory is supposed to initialize FIRST
factory = new ScriptEngineManager();
}

I found the way to fix this problem was to rename the project. If you give it a name with strange characters (in my case, :), it will have trouble locating your class. I don't know if this rule applies to numbers, but try renaming the project or making a new one and copying the files. Name it without any numbers or special characters.

I solved this error by closing the project, removing it from eclipse and then importing it again.
Might be a little simpler than to redo the whole workspace setup.

I had this issue after upgrading to the Eclipse 2019-12 release. Somehow the command line to launch the JVM got too long and I had to enable the jar-classpath option in the run configuration (right click on file -> run as -> run configs).

I read so many blogs and tried so many tricks but my problem not resolved. I was able to run the code but not able to generate the jar file. :( Sad..
But I tried something which might be very silly but worked for me and bought eclipse on trace. What I did was..
Just deleted the main method from the class. Saved it. Did undo to bring the main class back. Tada... Issue resolved...
Just one think would like to say, keep your eclipse in "Build Autometically" mode.

Move your file into a subdirectory called cont

Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.

I solved my issue by doing this:
cut the entire main (CTRL X) out of the class (just for a few seconds),
save the class file (CTRL S)
paste the main back exactly at the same place (CTRL V)
Strangely it started working again after that.

It is possible to have 2 groovy-xxx-all.jar files by excample in lib directory. which makes that an app is not running

I had the same problem, this is my solution:
I manually deleted the bin folder of the project
Then I refreshed the project which recompiled the whole project and created a new bin with all .class files
I did it because when I performed Clean(project->clean) my .class files were not getting deleted. the above solution works for me hope its useful to others.

I had the same problem.I solved with following command maven:
mvn eclipse:eclipse -Dwtpversion=2.0
PS: My project is WTP plugin

If you are using a pre-defined run configuration, go to classpath and try "Restore Default Entries". This will reconfigure the classpath for that configuration.

This worked for me finally :
RUN -> RUN CONFIGURATIONS -> DELETE THE RUN CONFIGURATION
CLOSE ECLIPSE
REOPEN ECLIPSE
CREATE RUN CONFIGURATION AGAIN.
Tadaaaa !! It works

Related

Java cannot access class, class file not found

When I try to make a project in IntelliJ I receive the following error on this line:
Sentence sent = new Sentence();
sent.emptySegments();
Error:
Error:(151, 10) java: cannot access javax.xml.bind.RootElement
class file for javax.xml.bind.RootElement not found
Sentence is a class which implements the RootElement interface
import javax.xml.bind.RootElement;
...
public class Sentence extends MarshallableRootElement implements RootElement {
All packages exist and I can jump to declaration of each interface or class but I don't know why IntellJ says it cannot access or find them? However RootElement is an interface and not a class
public interface RootElement extends Element {
void validate() throws StructureValidationException;
}
The above declaration is in a jar file named jaxb-rt-1.0-ea.jar and it exists in the Project librarians.
Try this
Go to File
Invalidate Caches/Restart
You can choose only Invalidate and restart
(See Invalidate caches on IntelliJ's manual)
The project contained several modules. While the library was added to the project libraries, some modules lacked it in their dependency part. So I solved the problem using the following steps in IntelliJ
Creating a module library and adding it to the module dependencies:
Open the Project Structure dialog (e.g. Ctrl+Shift+Alt+S).
In the left-hand pane of the dialog, select Modules.
In the pane to the right, select the module of interest.
In the right-hand part of the dialog, on the Module page, select the Dependencies tab.
On the Dependencies tab, click + (on the top right) and select Jars or directories.
In the dialog that opens, select the necessary files and folders. These may
be individual .class and .java files, directories and archives
(.jar and .zip) containing such files as well as directories with
Java native libraries (.dll, .so or .jnilib).
Click OK. If necessary, select the Export option and change the dependency scope.
Click OK in the Project Structure dialog.
File -> Invalidate Caches/ Restart
this worked for my after long hours of effectiveless
Rebuilding project worked for me.
Deleting the .idea folder and then running Invalidate Caches/Restart worked for me.
It also may be because you don't have dependencies in classpath, which used in dependencies.
For example: you use library A, but class you're using from A has superclass from library B. But you didn't add B to classpath.
If it is a single file, you can try deleting the file and undoing it. It seems to reindex that particular file alone, which is much faster than Invalidate Caches/Restart. As a precautionary measure, you can take a backup of the file before deleting, just in case if something goes awry.
Another reason might be different versions of same library with more/less methods. This happened for me with Gradle. Sometimes it compiles fine and sometimes, it doesn't. Just find and remove the unnecessary ones.
My Gradle/IntelliJ "big hammer"
(Optional, but preferred). Close all instances of IntelliJ or any other Java IDE.
delete the ".idea" folder (<< intellij specific, or whatever "workspace" folder your IDE uses)
..............
./gradlew --stop
OR
gradle --stop
(now delete the folders)
rm -rf $HOME/.gradle/caches/
rm -rf $HOME/.gradle/build-cache-tmp/
(now resume normal gradlew commands like:)
./gradlew clean build
For me just worked, turn off windows defender / add exclusion project folder / idea process.
Similar problem can happen if a library is imported with maven scope runtime.
In such case it isn't accessible by your classes located under src/main/java.
Only classes in src/test/java can directly use runtime dependencies.
I removed this location "amazonaws" file and clean install later run
/Users/testuser/.m2/repository/com/amazonaws
If you've made it this far because rebuilding or invalidating the cache didn't work work you, I found that deleting the class and adding a new one with the same code worked.
In my case there was an old .iml file in the module causing these problems. So if nothing else worked for you, try looking for one.
⬇ Download the last version of IntelliJ.
▶ Install it.
Worked for me. ✌

Java - Could not find the main class - reinstall didn't work

I got weird java error. When I try to run my code there appears window with:
Could not find the main class..
I have tried to reinstall java, but it
didn't help. Path to /bin directory is set properly. Can you help me ?
It happened with friend before and the reason was selecting right jre within project setup stage.
When you setup your project be sure you selected your right JRE -> Use a project specific JRE :jre1.8.0_31 something like this.
Isupposed that you have main method , also you did not delete or miss up with your source files.

Netbeans - Error: Could not find or load main class

So I'm making a java application in Neatbeans 7.4, been working at it for a while, everything was fine, running the project worked fine, but now when I hit run project, I get the error
Error: Could not find or load main class phleveledit.MainWindow
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I can't think of what I did right before this started happening, so I don't know what I should change.. The code doesn't appear to have any errors. Here's a screenshot of the IDE+project folder
Image (http://puu.sh/5ldYB) :
Any ideas?
Edit: Unfortunately I happened to fix this problem by removing some code, which probably had some errors Netbeans couldn't detect, but I don't know what was exactly wrong so can't vote on a correct answer.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Clean an build your project
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Just close the Netbeans. Go to C:\Users\YOUR_PC_NAME\AppData\Local\Netbeans and delete the Cache folder. The open the Netbeans again and run the project.
It works like magic for me.
(AppData folder might be hidden probably, if so, you need to make it appear in Folder Options).
You can :
RightClick on project node and go to Set configuration
Select the main class for your application.
Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
User\.netbeans\SOME_NUMBER_reflecting_your_version\var\cache\index\
Sometimes due to out of memory space error, NetBeans does not load or find main class.
If you have tried setting the properties and still it is not working then try
Select the project from the project explorer
Click on Run in the Menu Bar
Click on Compile
It worked for me.
This condition happens to me every 6-months or so. I think it happens when closing NetBeans under very low memory conditions. I discovered that it could be easily corrected by (1) Rename your project, including its folder name using right-click on project explorer's project name---I put a simple suffix on the original name ("_damaged"). (2) Try BUILD. If that is successful, which it is for me, give three cheers. (3) Repeat step (1) to restore the original project name. BUILD and RUN should start without trouble.
I guess that the 'rename the project and folder' process causes a special rediscovery of the applications main location.
Try to rename the package name and the class/jframe names... The clean and build the application.
Right Click on the package name
Go to Refactor
Select Rename
Give it a meaningful name, preferably all in small letters
Click on Refactor
Do the same for the class/jframe names.
Last Select Run from Menu
7.Select Clean and build main project
That should do it!!! All best
I had the same issue once. The problem was not in the code. The cause was... renaming the project folder to some other non supporting name. My project name was "MobStick" and I renamed it to "MobStick - May 26, 2014 04:00PM". Renaming it back to normal solved my problem.
I have run into this error a couple of times as well and for me the above solutions did not work. What does seem to work is going to the Project Properties, and under Compiling toggling Compile on Save.
Using NetBeans 8.1, I got the dread
Error: Could not find or load main class
from carelessly leaving an empty line in the Project Properties > Run > VM Options field. Until you click in the field, you may not see the caret flashing out of place. Remove the empty line to restore equanimity.
I just ran into this problem. I was running my source from the command line and kept getting the same error. It turns out that I needed to remove the package name from my source code and then the command line compiler was happy.
The solutions above didn't work for me so maybe this will work for someone else with a similar problem.
I had the same problem, I had the package and class named the same. I renamed the class, then clean and build. Then I set the main class in the "run" under the properties of the project. I works now.
I found the following steps useful:
Right-click on the project in the left toolbar.
Hover over the 'Set Configuration' item.
Click on 'Customize...'
Click on 'Browse...' by the 'Main Class:' item.
Select the correct class.
Click 'Select Main Class'.
Click 'OK'.
My problem was that, apparently, my package name was being listed twice. Selecting the class using the dialog changed 'aclass.MainClass' to just 'MainClass'.
Hope this helps,
-HewwoCraziness
Edit: This is expanding on Mary Martinez's answer.
You can solve it in these steps
Right-click on the project in the left toolbar.
Click on properties.
Click on Run
Click the browse button on the right side.(select your main class)
Click ok
Possible Fixes:
Fix 1
Go to project properties (right click on the folder of your project in netbeans)
On left tab where it shows the categories, click on the "Run" selection
Then click on Browse to find the Main class you use on your project
Fix 2
Go to C:\Users\name\AppData\Local\Netbeans
delete the Cache folder.
Rebuild and Run
Fix 3
Download most recent version of Netbeans
Fix 4
Download most recent version of JDK and configure Netbeans to use that
I had the same problem for 3,4 days. On my PC my Jar file snapshot would give me this error while on my laptop it would work fine, I tried all the tricks shown above and on other forums like deleting cache, selecting main project file, etc, but somehow I was sure the reason it cannot find the main class when I would execute the JAR file was may be due to classpath issue in maven configuration, and I was right and I fixed it using following steps:
Right-click on the project, and go to the properties
Inside the properties go to Actions
On the right side in Actions select "Run Project" and you will see properties below
Inside "Set Properties" make sure exec.args=classpath %classpath "package_name"
In my case, the package name was accompanied by the main class. So my main class was Login while the package name was com.mycompany.islamic_center_app1, When I checked the entry was
com.mycompany.islamic_center_app1.Login
All I did was remove ".Login" from com.mycompany.islamic_center_app1 and it was fixed, no more errors.
close netbeans.
open netbeans again.
choose new project>>java application.
click next.
deselect create main class.
now make the application
clean build run
For more reference watch this video
try this it work out for me perfectly
go to project and right click on your java file at the right corner,
go to properties,
go to run,
go to browse, and then
select Main class.
now you can run your program again.
I had the same problem and I moved the project to a location where the path had no none-english letter and that fixed the problem
if you are on window os, then try to start NetBeans via administrative mode. right click on NetBeans icon and "Run as Administrative".
If none of the above works (Setting Main class, Clean and Build, deleting the cache) and you have a Maven project, try:
mvn clean install
on the command line.
Had the same problem here. Usually Clean and Build solves much of the problem. It happened to be caused by a wrongly installed plugin.
I faced the similar issue with Netbeans 10 and JDK 1.8.
I was not able to choose the right class to launch the project
When I compile or run the project, it shows me the Class name as "initializing view, please wait ...", I could not select the class name.
The issue was resolved with the NetBeans11.3, I am able to choose the correct Class file without any other changes, and the project is launched without any issues.
I had the same issue but none of this thread's solutions worked for me. Finally, it was OneDrive that caused the issue (for once more). So, I simply moved the NetBeansProjects folder from Documents which is synced with OneDrive, to C:\Users\yourName\AppData\Local\NetBeans (selected this path as there is already a NetBeans folder) and that was it, case closed.
If you also have NetBeansProjects to a OneDrive syncing folder it is worth trying this solution, just be sure that the path you will select is not synced with OneDrive. Also, remember to close Netbeans before making the folder change and after you move the folder to the new path you need just to open Netbeans again, go to file menu/open project and select your project from the new path.

Could not find or load main class Swing Java

Error: Could not find or load main class jewelleryerpapplication.GUI.ERPMainMenu
Java Result: 1
Actually i am using Net Beans 7.1 and in that i am continuosly getting the same error but un able to get the solution for that even after installing the latest update for that. The solution which i got from some body that create new project and copy the source and library foldes in that Project from the previous which generate the above error. this solution works for me but i need some simpler solution for this problem.Lot of thanks in advance.
Don't Forget To Give UpVote It If It Helps.
Right click on project node, go to Set configuration, select the main class for your application. Then clean and build.
Even if this doesn't solve your problem, then delete the Netbeans cache by deleting the (index) folder
User\.netbeans\6.9\var\cache\index\
I think that the following is happening:
If this is a third party application, you have not included some jar files on your class path;
Or, (which in my opinion is the most likely) you do not have a method which has this signature: public static void main(String[] args). This method defines the main entry point for your application, not having it might cause that error when you try and run the project. To my knowledge, Netbeans creates a main class with such a method automatically whenever you create a new project. This might be the reason why you are not having this exception when you create a new Project and throw everything in it.
You might be having an issue with Netbeans itself. You can start by either checkin gout this previous SO thread in which a similar (I think) issue is being discussed, or else, as a final resort, you might want to remove Netbeans and all its files, and install an earlier version. You can also try and see if you get the same issue if you use a different IDE such as Eclipse.
the solution is,right click your package in netbeans,go to properties,source now go to the jre option and choose your version,the programme will now run.

Eclipse ClassNotFoundException

Everything works fined, but suddenly eclipse stopped execute and junit tests or even main method, when i run them using run as - > Java application, run as -> junit test
It simply throws error
Caused by: java.lang.ClassNotFoundException: package.ClassName
whene ClassName - is class from where i trying to run method main.
It affect only one of my projects ... Different workspaces works fine, other project in same workspace works fine as well.
I'm sure if i recreate current project, error will gone. But the adjustments of this project in eclipse is really hard, so i want to avoid it.
Any clue?
The ClassName is not in the Class Path, if you start from console you should use -cp parameter , if from eclipse, please add ClassName to the sources of current(start) project.
Thanks to adarshr, I was able to look at the Problems window and determine that the build was failing because it could not find a class I had written.
I had used the MS TFS plugin to create a "shelveset" and it was supposed to have removed my pending changes in the process. However, this integration with the TFS snapin and Eclipse is obviously not well implemented, since the Eclipse project still thought the file existed and was complaining that it could not be compiled.
I went and manually deleted those "files" or "non-existing files" from the Eclipse project (that I thought I had removed with the shelveset action) and the problem was solved.
Also....
Another annoying things is that the Tomcat error I was getting by trying to debug within Eclipse was like this:
SEVERE: Error configuring application listener of class
com.CompanyName.ProjectName.servlet.StartupConfigListener
java.lang.ClassNotFoundException:
com.CompanyName.ProjectName.servlet.StartupConfigListener at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
In reality, there was no problem at all with StartupConfigListener.java!! The build failed due to the OTHER problems I mentioned above, and therefore I guess this was the first class it attempted to load and failed.... because the entire project hadn't been able to compile perhaps?
(Here's to hoping my next project is using Visual Studio instead of Eclipse!)
Ok, I finally figured it out. The problem was with installed JRE in eclipse setting. I was playing around with this setting and changed installed JRE to JDK, and for some reason it broke the eclipse project.
You can also try going back to the basics. Check your command line and VM args. I've had this situation where a VM arg I was passing in was a path to a file that had a space in the path, and I had forgotten to include the full path in quotes. So e.g., if my arg looked something like
-DFILE=C:\Documents and Settings\myfile
...I'd get a java.lang.NoClassDefFoundError caused by a java.lang.ClassNotFoundException.

Categories