Error: Could not find or load main class (MAC) [duplicate] - java

This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 7 years ago.
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
However, when I try to run the following:
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
I get the following error: "Error: Could not find or load main class SpatialModel
". My SpatialModel.java code does contain a 'main' method (below), so I'm not sure what the problem is - can anyone please help me out? Thanks.
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class SpatialModel {
private VensimHelper vh;
public static final String DLL_LIBNAME_PARAM = "vensim_lib_nam";
public static final String MODEL_PATH_PARAM = "vensim_model_path";
private final static int VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT = 10;
public SpatialModel() throws SpatialException {
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if(libName == null || libName.trim().equals("")) {
log.error("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
throw new SpatialException("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
}
if(modelPath == null || modelPath.trim().equals("")) {
log.error("Model path has to set with -D" + MODEL_PATH_PARAM);
throw new SpatialException("Model path ahs to be set with -D" + MODEL_PATH_PARAM);
}
for (int i = 0; i < VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT && vh == null; i++) {
try {
log.info("creating new vensim helper\n\tdll lib: " + libName + "\n\tmodel path: " + modelPath);
vh = new VensimHelper(libName, modelPath);
} catch (Throwable e) {
log.error("An exception was thrown when initializing Vensim, try: " + i, e);
}
}
if (vh == null) {
throw new SpatialException("Can't initialize Vensim");
}
}
public static void main(String[] args) throws VensimException {
long before = System.currentTimeMillis();
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if (libName == null) {
libName = "libvensim";
}
if(modelPath == null) {
modelPath = "~/BassModel.vmf";
}
System.setProperty(DLL_LIBNAME_PARAM, libName);
System.setProperty(MODEL_PATH_PARAM, modelPath);
if (args.length > 0 && args[0].equals("info")) {
System.out.println(new VensimHelper(libName, modelPath).getVensimInfo());
} else if (args.length > 0 && args[0].equals("vars")) {
VensimHelper helper = new VensimHelper(libName, modelPath);
String[] vars = helper.getVariables();
for (String var : vars) {
System.out.println(helper.getVariableInfo(var));
}
} else {
File f = new File(".");
System.out.println(f.getAbsolutePath());
SpatialModel sm = new SpatialModel();
}
System.out.println("Execution time: " + (System.currentTimeMillis() - before));
}
}

You must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . to your classpath.
Note that the Windows classpath separator is a semi-colon, i.e. a ;.

If the class is in a package
package thepackagename;
public class TheClassName {
public static final void main(String[] cmd_lineParams) {
System.out.println("Hello World!");
}
}
Then calling:
java -classpath . TheClassName
results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:
java -classpath . thepackagename.TheClassName
And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.
To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”

You can try these two when you are getting the error: 'could not find or load main class'
If your class file is saved in following directory with HelloWorld program name
d:\sample
java -cp d:\sample HelloWorld
java -cp . HelloWorld

I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars

You have to include classpath to your javac and java commands
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
file is located inside "src/com/test/Hello.java"
from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
In windows the same thing will be working too, I already tried

If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.

You have to set the classpath if you get the error:
Could not find or load main class XYZ
For example:
E:\>set path="c:\programfiles\Java\jdk1.7.0_17\bin"
E:\>set classpath=%classpath%;.;
E:\>javac XYZ.java
E:\>java XYZ

I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class:
javac HelloWorld.java && java HelloWorld

Check your BuildPath, it could be that you are referencing a library that does not exist anymore.

If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/.
In my case I created my project in Eclipse which defaults to src (rather than src/main/java/.
So I ended up with something like mypackage.morepackage.myclass and a directory structure looking like src/mypackage/morepackage/myclass, which inherently has nothing wrong. But when you run mvn clean install it will look for src/main/java/mypackage/morepackage/myclass. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.

I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

If you try to run a java application which needs JDK 1.6 and you are trying to run on JDK 1.4, you will come across this error. In general, trying to run a Java application on old JRE may fail. Try installing new JRE/JDK.

Problem is not about your main function. Check out for
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
output and run it.

Project > Clean and then make sure BuildPath > Libraries has the correct Library.

java -verbose:class HelloWorld might help you understand which classes are being loaded.
Also, as mentioned before, remember to call the full qualified name (i.e. include package).

I was using Java 1.8, and this error suddenly occurred when I pressed "Build and clean" in NetBeans. I switched for a brief moment to 1.7 again, clicked OK, re-opened properties and switched back to 1.8, and everything worked perfectly.
I hope I can help someone out with this, as these errors can be quite time-consuming.

This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.

If so simple than many people think, me included :)
cd to Project Folder/src/package there you should see yourClass.java then run javac yourClass.java which will create yourClass.class then cd out of the src folder and into the build folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows

If you are using Eclipse... I renamed my main class file and got that error. I went to "Run As" configurator and under the class path for that project, it had listed both files in the class path. I removed old class that I renamed and left the class that had the new name and it compiled and ran just fine.

This solved the issue for me today:
cd /path/to/project
cd build
rm -r classes
Then clean&build it and run the individual files you need.

I have a similar problem in Windows, it's related to the classpath. From the command line, navigate until the directory where it's located your Java file (*.java and *.class), then try again with your commands.

I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.

Related

How to run StanfordCoreNlpDemo.java

I successfully compiled StanfordCoreNlpDemo by running:
javac -cp "*" StanfordCoreNlpDemo.java
and it compiled successfully. I then tried to run it with:
java -cp "*" StanfordCoreNlpDemo
I then received the following error:
Error: Could not find or load main class StanfordCoreNlpDemo
I realize this is a CLASSPATH issue so I tried to add the path to the folder:
/some/path/stanford-corenlp-full-2016-10-31/*
Nonetheless, I still get the same error. How do I run StanfordCoreNlpDemo.java?
This is not a problem of StanfordCoreNlpDemo program because I ran that code in Netbeans before. The problem seems associated with classpath issue.
Since the StanfordCoreNlpDemo.java file belongs to a package
package package edu.stanford.nlp.pipeline.demo;
public class StanfordCoreNlpDemo {
public static final void main(String[] args) throws IOException {
// code goes here
}
}
Then calling the following results in Error: Could not find or load main class TheClassName.
java -cp . StanfordCoreNlpDemo
It must be called with its fully-qualified name:
java -cp . edu.stanford.nlp.pipeline.demo.StanfordCoreNlpDemo
And this edu.stanford.nlp.pipeline.demo directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which edu.stanford.nlp.pipeline.demo exists.
Reference
https://stackoverflow.com/a/29331827/5352399
https://stackoverflow.com/a/18093929/5352399

How to compile and run a .java file which is set in a package? [duplicate]

This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 7 years ago.
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
However, when I try to run the following:
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
I get the following error: "Error: Could not find or load main class SpatialModel
". My SpatialModel.java code does contain a 'main' method (below), so I'm not sure what the problem is - can anyone please help me out? Thanks.
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class SpatialModel {
private VensimHelper vh;
public static final String DLL_LIBNAME_PARAM = "vensim_lib_nam";
public static final String MODEL_PATH_PARAM = "vensim_model_path";
private final static int VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT = 10;
public SpatialModel() throws SpatialException {
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if(libName == null || libName.trim().equals("")) {
log.error("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
throw new SpatialException("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
}
if(modelPath == null || modelPath.trim().equals("")) {
log.error("Model path has to set with -D" + MODEL_PATH_PARAM);
throw new SpatialException("Model path ahs to be set with -D" + MODEL_PATH_PARAM);
}
for (int i = 0; i < VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT && vh == null; i++) {
try {
log.info("creating new vensim helper\n\tdll lib: " + libName + "\n\tmodel path: " + modelPath);
vh = new VensimHelper(libName, modelPath);
} catch (Throwable e) {
log.error("An exception was thrown when initializing Vensim, try: " + i, e);
}
}
if (vh == null) {
throw new SpatialException("Can't initialize Vensim");
}
}
public static void main(String[] args) throws VensimException {
long before = System.currentTimeMillis();
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if (libName == null) {
libName = "libvensim";
}
if(modelPath == null) {
modelPath = "~/BassModel.vmf";
}
System.setProperty(DLL_LIBNAME_PARAM, libName);
System.setProperty(MODEL_PATH_PARAM, modelPath);
if (args.length > 0 && args[0].equals("info")) {
System.out.println(new VensimHelper(libName, modelPath).getVensimInfo());
} else if (args.length > 0 && args[0].equals("vars")) {
VensimHelper helper = new VensimHelper(libName, modelPath);
String[] vars = helper.getVariables();
for (String var : vars) {
System.out.println(helper.getVariableInfo(var));
}
} else {
File f = new File(".");
System.out.println(f.getAbsolutePath());
SpatialModel sm = new SpatialModel();
}
System.out.println("Execution time: " + (System.currentTimeMillis() - before));
}
}
You must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . to your classpath.
Note that the Windows classpath separator is a semi-colon, i.e. a ;.
If the class is in a package
package thepackagename;
public class TheClassName {
public static final void main(String[] cmd_lineParams) {
System.out.println("Hello World!");
}
}
Then calling:
java -classpath . TheClassName
results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:
java -classpath . thepackagename.TheClassName
And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.
To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”
You can try these two when you are getting the error: 'could not find or load main class'
If your class file is saved in following directory with HelloWorld program name
d:\sample
java -cp d:\sample HelloWorld
java -cp . HelloWorld
I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
You have to include classpath to your javac and java commands
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
file is located inside "src/com/test/Hello.java"
from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
In windows the same thing will be working too, I already tried
If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.
You have to set the classpath if you get the error:
Could not find or load main class XYZ
For example:
E:\>set path="c:\programfiles\Java\jdk1.7.0_17\bin"
E:\>set classpath=%classpath%;.;
E:\>javac XYZ.java
E:\>java XYZ
I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class:
javac HelloWorld.java && java HelloWorld
Check your BuildPath, it could be that you are referencing a library that does not exist anymore.
If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/.
In my case I created my project in Eclipse which defaults to src (rather than src/main/java/.
So I ended up with something like mypackage.morepackage.myclass and a directory structure looking like src/mypackage/morepackage/myclass, which inherently has nothing wrong. But when you run mvn clean install it will look for src/main/java/mypackage/morepackage/myclass. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.
I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
If you try to run a java application which needs JDK 1.6 and you are trying to run on JDK 1.4, you will come across this error. In general, trying to run a Java application on old JRE may fail. Try installing new JRE/JDK.
Problem is not about your main function. Check out for
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
output and run it.
Project > Clean and then make sure BuildPath > Libraries has the correct Library.
java -verbose:class HelloWorld might help you understand which classes are being loaded.
Also, as mentioned before, remember to call the full qualified name (i.e. include package).
I was using Java 1.8, and this error suddenly occurred when I pressed "Build and clean" in NetBeans. I switched for a brief moment to 1.7 again, clicked OK, re-opened properties and switched back to 1.8, and everything worked perfectly.
I hope I can help someone out with this, as these errors can be quite time-consuming.
This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.
If so simple than many people think, me included :)
cd to Project Folder/src/package there you should see yourClass.java then run javac yourClass.java which will create yourClass.class then cd out of the src folder and into the build folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
If you are using Eclipse... I renamed my main class file and got that error. I went to "Run As" configurator and under the class path for that project, it had listed both files in the class path. I removed old class that I renamed and left the class that had the new name and it compiled and ran just fine.
This solved the issue for me today:
cd /path/to/project
cd build
rm -r classes
Then clean&build it and run the individual files you need.
I have a similar problem in Windows, it's related to the classpath. From the command line, navigate until the directory where it's located your Java file (*.java and *.class), then try again with your commands.
I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.

Error: Could not find or load main class com.sun.tools.javac.Main [duplicate]

This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 7 years ago.
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
However, when I try to run the following:
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
I get the following error: "Error: Could not find or load main class SpatialModel
". My SpatialModel.java code does contain a 'main' method (below), so I'm not sure what the problem is - can anyone please help me out? Thanks.
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class SpatialModel {
private VensimHelper vh;
public static final String DLL_LIBNAME_PARAM = "vensim_lib_nam";
public static final String MODEL_PATH_PARAM = "vensim_model_path";
private final static int VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT = 10;
public SpatialModel() throws SpatialException {
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if(libName == null || libName.trim().equals("")) {
log.error("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
throw new SpatialException("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
}
if(modelPath == null || modelPath.trim().equals("")) {
log.error("Model path has to set with -D" + MODEL_PATH_PARAM);
throw new SpatialException("Model path ahs to be set with -D" + MODEL_PATH_PARAM);
}
for (int i = 0; i < VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT && vh == null; i++) {
try {
log.info("creating new vensim helper\n\tdll lib: " + libName + "\n\tmodel path: " + modelPath);
vh = new VensimHelper(libName, modelPath);
} catch (Throwable e) {
log.error("An exception was thrown when initializing Vensim, try: " + i, e);
}
}
if (vh == null) {
throw new SpatialException("Can't initialize Vensim");
}
}
public static void main(String[] args) throws VensimException {
long before = System.currentTimeMillis();
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if (libName == null) {
libName = "libvensim";
}
if(modelPath == null) {
modelPath = "~/BassModel.vmf";
}
System.setProperty(DLL_LIBNAME_PARAM, libName);
System.setProperty(MODEL_PATH_PARAM, modelPath);
if (args.length > 0 && args[0].equals("info")) {
System.out.println(new VensimHelper(libName, modelPath).getVensimInfo());
} else if (args.length > 0 && args[0].equals("vars")) {
VensimHelper helper = new VensimHelper(libName, modelPath);
String[] vars = helper.getVariables();
for (String var : vars) {
System.out.println(helper.getVariableInfo(var));
}
} else {
File f = new File(".");
System.out.println(f.getAbsolutePath());
SpatialModel sm = new SpatialModel();
}
System.out.println("Execution time: " + (System.currentTimeMillis() - before));
}
}
You must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . to your classpath.
Note that the Windows classpath separator is a semi-colon, i.e. a ;.
If the class is in a package
package thepackagename;
public class TheClassName {
public static final void main(String[] cmd_lineParams) {
System.out.println("Hello World!");
}
}
Then calling:
java -classpath . TheClassName
results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:
java -classpath . thepackagename.TheClassName
And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.
To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”
You can try these two when you are getting the error: 'could not find or load main class'
If your class file is saved in following directory with HelloWorld program name
d:\sample
java -cp d:\sample HelloWorld
java -cp . HelloWorld
I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
You have to include classpath to your javac and java commands
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
file is located inside "src/com/test/Hello.java"
from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
In windows the same thing will be working too, I already tried
If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.
You have to set the classpath if you get the error:
Could not find or load main class XYZ
For example:
E:\>set path="c:\programfiles\Java\jdk1.7.0_17\bin"
E:\>set classpath=%classpath%;.;
E:\>javac XYZ.java
E:\>java XYZ
I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class:
javac HelloWorld.java && java HelloWorld
Check your BuildPath, it could be that you are referencing a library that does not exist anymore.
If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/.
In my case I created my project in Eclipse which defaults to src (rather than src/main/java/.
So I ended up with something like mypackage.morepackage.myclass and a directory structure looking like src/mypackage/morepackage/myclass, which inherently has nothing wrong. But when you run mvn clean install it will look for src/main/java/mypackage/morepackage/myclass. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.
I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
If you try to run a java application which needs JDK 1.6 and you are trying to run on JDK 1.4, you will come across this error. In general, trying to run a Java application on old JRE may fail. Try installing new JRE/JDK.
Problem is not about your main function. Check out for
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
output and run it.
Project > Clean and then make sure BuildPath > Libraries has the correct Library.
java -verbose:class HelloWorld might help you understand which classes are being loaded.
Also, as mentioned before, remember to call the full qualified name (i.e. include package).
I was using Java 1.8, and this error suddenly occurred when I pressed "Build and clean" in NetBeans. I switched for a brief moment to 1.7 again, clicked OK, re-opened properties and switched back to 1.8, and everything worked perfectly.
I hope I can help someone out with this, as these errors can be quite time-consuming.
This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.
If so simple than many people think, me included :)
cd to Project Folder/src/package there you should see yourClass.java then run javac yourClass.java which will create yourClass.class then cd out of the src folder and into the build folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
If you are using Eclipse... I renamed my main class file and got that error. I went to "Run As" configurator and under the class path for that project, it had listed both files in the class path. I removed old class that I renamed and left the class that had the new name and it compiled and ran just fine.
This solved the issue for me today:
cd /path/to/project
cd build
rm -r classes
Then clean&build it and run the individual files you need.
I have a similar problem in Windows, it's related to the classpath. From the command line, navigate until the directory where it's located your Java file (*.java and *.class), then try again with your commands.
I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.

java.lang.NoClassDefFoundError

I'm learning Java am having trouble running an example program.
I have two files:
GoodDog.java:
class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;
}
void bark() {
if (size > 60) {
System.out.println("Wooof! WoooF!");
} else if (size > 14) {
System.out.println("Ruff! Ruff!");
} else {
System.out.println("Yip! Yip!");
}
}
}
GoodDogTestDrive.java:
class GoodDogTestDrive {
public static void main (String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println("Dog one: " + one.getSize () );
System.out.println("Dog two: " + two.getSize () );
one.bark();
two.bark();
}
}
They are typed out exactly the way they are in the book and compile without issue. When I try to run GoodDogTestDrive I get this:
nephi-shields-mac-mini:/Developer/MyProjects/GoodDog nephishields$ java GoodDogTestDrive.class
java.lang.NoClassDefFoundError: GoodDogTestDrive/class
Exception in thread "main" nephi-shields-mac-mini:/Developer/MyProjects/GoodDog nephishields$
What am I doing wrong?
Don't include the .class in the command:
java GoodDogTestDrive
It is important to note that while the resolution was simple for this problem case (simply removing .class from the Java command line), java.lang.NoClassDefFoundError can be hard to pinpoint in the context of Java Web application developments.
This Java exception means that a “runtime” Java class could not be loaded and/or found in the current Thread context classloader. This is normally the results of:
Missing library in your runtime classpath.
Static {} block code initializer execution failure (preventing class loading of the affected class).
JAR file packaging / class loader tree problems such as mix of JAR files deployed at the child & parent class loader.
It is recommended for any Java beginner to properly understand this type of problem in anticipation of future troubleshooting episodes.
just run the program with "java yourClass".
Do not use .class in the end.
Try it and let us know.
If the GoodDog class file is not located at the current working directory you will need to set the classpath on your java command....
java GoodDogTestDrive -cp ./path/to/gooddog/
Issue-java.lang.NoClassDefFoundError
Root Cause: Incorrect Java path set in Environment Variable Section
Solution: Set correct JAVA_HOME Path
Steps->Environment Variable Setting (My Comp-Right Click ->Properties->Env Variable->Advance Tab ->Variable)
Create new JAVA_HOME Environment Variable.
JAVA_HOME **.;C:\Program Files (x86)\Java\jdk1.6.0_14**
Set JAVA_HOME variable in PATH Variable section.
PATH %JAVA_HOME%\bin
Set JAVA_HOME variable in CLASSPATH Variable
CLASSPATH %JAVA_HOME%\jre\lib
Restart System
Verify all variable
echo %CLASSPATH%
echo %JAVA_HOME%
echo %PATH%
Compile java class javac Test.java
Run Java program java Test
Thrown if the JVM or a ClassLoader instance tries to load in the definition of a class (method call or creating a new instance) and no definition of the class could be found.
The reason for NoClassDefFoundError is that a particular class is not available on runtime but was available during compile time.
1.The class belongs to a missing JAR or JAVA file or JAR was not added into classpath.
2.Class is not available in Java Classpath.
3.NoClassDefFoundError in Java due to Exception in Static Initializer block. when your class perform some static initialization in static
block, and if static block throw an Exception, the class which is
referring to this class will get NoclassDefFoundError in Java.
4.Your Classpath, PATH or JAVA_HOME is not setup properly or JDK installation is not correct. which can be resolved by re-installing JDK.
5.Do a maven clean-install and simply restart your server with necessary Source(.java) files.
I was facing the same problem as you.
I resolved the problem like this:
Check the class path in evironment variables
I opened the project in navigator of eclipse and I checked the class files. My class files were in different folders not in the bin folder. I just copied the missing files into the bin folder then the problem was resolved.
Simply copying the missing .class files to bin directory of eclipse project resolved the problem.

javac error: Class names are only accepted if annotation processing is explicitly requested

I get this error when I compile my java program:
error: Class names, 'EnumDevices', are only accepted if annotation
processing is explicitly requested
1 error
Here is the java code (I'm running this on Ubuntu).
import jcuda.CUDA;
import jcuda.driver.CUdevprop;
import jcuda.driver.types.CUdevice;
public class EnumDevices {
public static void main(String args[]) {
CUDA cuda = new CUDA(true);
int count = cuda.getDeviceCount();
System.out.println("Total number of devices: " + count);
for (int i = 0; i < count; i++) {
CUdevice dev = cuda.getDevice(i);
String name = cuda.getDeviceName(dev);
System.out.println("Name: " + name);
int version[] = cuda.getDeviceComputeCapability(dev);
System.out.println("Version: " +
String.format("%d.%d", version[0], version[1]));
CUdevprop prop = cuda.getDeviceProperties(dev);
System.out.println("Clock rate: " + prop.clockRate + " MHz");
System.out.println("Threads per block: " + prop.maxThreadsPerBlock);
}
}
}
Here is the javac command:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
How do I compile this program?
You at least need to add the .java extension to the file name in this line:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
From the official faq:
Class names, 'HelloWorldApp', are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.
Also, in your second javac-example, (in which you actually included .java) you need to include the all required .jar-files needed for compilation.
I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.
This will also cause the "annotation processing" error:
javac myclass.Java
Instead, it should be:
javac myclass.java
Using javac ClassName.java to compile the program,
then use java ClassName to execute the compiled code. You can't mix javac with the ClassName only (without the java extension).
The error "Class names are only accepted if annotation processing is explicitly requested" can be caused by one or more of the following:
Not using the .java extension for your java file when compiling.
Improper capitalization of the .java extension (i.e. .Java) when compiling.
Any other typo in the .java extension when compiling.
When compiling and running at the same time, forgetting to use '&&' to concatenate the two commands (i.e. javac Hangman.java java Hangman). It took me like 30 minutes to figure this out, which I noticed by running the compilation and the running the program separately, which of course worked perfectly fine.
This may not be the complete list of causes to this error, but these are the causes that I am aware of so far.
I learned that you also can get this error by storing the source file in a folder named Java
chandan#cmaster:~/More$ javac New.java
chandan#cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error
So if you by mistake after compiling again use javac for running a program.
How you can reproduce this cryptic error on the Ubuntu terminal:
Put this in a file called Main.java:
public Main{
public static void main(String[] args){
System.out.println("ok");
}
}
Then compile it like this:
user#defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if
annotation processing is explicitly requested
1 error
It's because you didn't specify .java at the end of Main.
Do it like this, and it works:
user#defiant /home/user $ javac Main.java
user#defiant /home/user $
Slap your forehead now and grumble that the error message is so cryptic.
Perhaps you may be compiling with file name instead of method name....Check once I too made the same mistake but I corrected it quickly .....#happy Coding
first download jdk from https://www.oracle.com/technetwork/java/javase/downloads/index.html.
Then in search write Edit the System environment variables
In open window i push bottom called Environment Variables
Then in System variables enter image description here
Push bottom new
In field new variables write "Path"
In field new value Write directory in folder bin in jdk like
"C:\Program Files\Java\jdk1.8.0_191\bin"
but in my OS work only this "C:\Program Files\Java\jdk1.8.0_191\bin\javac.exe"
enter image description here
press ok 3 times
Start Cmd.
I push bottom windows + R.
Then write cmd.
In cmd write "cd (your directory with code )" looks like C:\Users\user\IdeaProjects\app\src.
Then write "javac (name of your main class for your program).java" looks like blabla.java
and javac create byte code like (name of your main class).class in your directory.
last write in cmd "java (name of your main class)" and my program start work
To avoid this error, you should use javac command with .java extension.
Javac DescendingOrder.java <- this work perfectly.
I created a jar file from a Maven project
(by write mvn package or mvn install )
after that i open the cmd , move to the jar direction and then
to run this code the
java -cp FILENAME.jar package.Java-Main-File-Name-Class
Edited : after puting in Pom file declar the main to run the code :
java -jar FILENAME.JAR
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
Incorrect:
Correct:

Categories

Resources