Running two different Quartz Applications connecting same oracle schema [duplicate] - java

I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:
Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I think I might have the Main.java file in the wrong folder.
Here is the directory hierarchy:
graphics
├ Main.java
├ shapes
| ├ Square.java
| ├ Triangle.java
├ linepoint
| ├ Line.java
| ├ Point.java
├ spaceobjects
| ├ Cube.java
| ├ RectPrism.java
And here is Main.java:
import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;
public class Main {
public static void main(String args[]) {
Square s = new Square(2, 3, 15);
Line l = new Line(1, 5, 2, 3);
Cube c = new Cube(13, 32, 22);
}
}
What am I doing wrong here?
UPDATE
After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.
Really late UPDATE #2
I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.

After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader), which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use.
Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.
For example, if you had a class com.example.Foo, after compiling you would have a class file Foo.class. Say for example your working directory is .../project/. That class file must be placed in .../project/com/example, and you would set your classpath to .../project/.
Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.

I'd like to correct the perspective of others on NoClassDefFoundError.
NoClassDefFoundError can occur for multiple reasons like:
ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
Class file located, but Exception raised while initializing static variables
Class file located, Exception raised while initializing static blocks
In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes JAR file or to its package folder.
What does it mean by saying "available in compile time"?
The referenced class is used in the code. E.g.: Two classes, A and B (extends A). If B is referenced directly in the code, it is available at compile time, i.e., A a = new B();
What does it mean by saying "not available at compile time"?
The compile time class and runtime class are different, i.e., for example base class is loaded using classname of child class for example
Class.forName("classname")
E.g.: Two classes, A and B (extends A). Code has
A a = Class.forName("B").newInstance();

If you got one of these errors while compiling and running:
NoClassDefFoundError
Error: Could not find or load main class hello
Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- Solution -----------------------
The problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On compiling process, use this command:
javac -d . [FileName.java]
To run the class, please use this command:
java [Package].[ClassName]

NoClassDefFoundError means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime.
If you're using Eclipse, make sure you have the shapes, linepoints and the spaceobjects as entries in the .classpath file.

java.lang.NoClassDefFoundError
indicates that something was found at compile time, but not at run time. Maybe you just have to add it to the classpath.

NoClassDefFoundError in Java:
Definition:
NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:
Exception in thread "main" java.lang.NoClassDefFoundError
Possible Causes:
The class is not available in Java Classpath.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Any start-up script is overriding Classpath environment variable.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Possible Resolutions:
Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.
The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.
Resources:
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE
java.lang.NoClassDefFoundError – How to solve No Class Def Found Error

The no class definition exception occurs when the intended class is not found in the class path.
At compile time class: Class was generated from the Java compiler, but somehow at run time the dependent class is not found.
Let’s go through one simple example:
public class ClassA{
public static void main(String args[]){
// Some gibberish code...
String text = ClassB.getString();
System.out.println("Text is: " + text);
}
}
public class ClassB{
public static String getString(){
return "Testing some exception";
}
}
Now let's assume that the above two Java source code are placed in some folder, let's say "NoClassDefinationFoundExceptionDemo"
Now open a shell (assuming Java is already being set up correctly)
Go to folder "NoClassDefinationFoundExceptionDemo"
Compile Java source files
javac ClassB
javac ClassA
Both files are compiled successfully and generated class files in the same folder as ClassA.class and ClassB.class
Now since we are overriding ClassPath to the current working director, we execute the following command
java -cp . ClassA
and it worked successfully and you will see the output on the screen
Now let's say, you removed ClassB.class file from the present directory.
And now you execute the command again.
java -cp . ClassA Now it will greet you with NoClassDefFoundException. As ClassB which is a dependency for ClassA is not found in the classpath (i.e., the present working directory).

If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.
When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.
cd out
java -classpath . com.blahcode.Main

I have faced with the problem today. I have an Android project and after enabling multidex the project wouldn't start anymore.
The reason was that I had forgotten to call the specific multidex method that should be added to the Application class and invoked before everything else.
MultiDex.install(this);
Follow this tutorial to enable multidex correctly. https://developer.android.com/studio/build/multidex.html
You should add these lines to your Application class
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}

After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing NetBeans altogether and reopening the project there were no error reports.

This answer is specific to a java.lang.NoClassDefFoundError happening in a service:
My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.
However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.
The eventual solution: Restart the service!
It appears that the rpm upgrade invalidated the service's file handle on the underlying JAR file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.

For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved.
How did I discover the issue? Because I ran my project using the Selenium native Firefox driver with an old version of FF included with my application. I realized the problem was incompatibility between browser and driver.
Hope this can help anyone with a similar issue as mine, that generated this same Error Message.

If you are "starting" a class from a JAR file, make sure to start with the JAR full path. For example, (if your "main class" is not specified in Manifest):
java -classpath "./dialer.jar" com.company.dialer.DialerServer
And if there are any dependencies, such dependencies to other JAR files, you can solve such a dependency
either by adding such JAR files (full path to each JAR file) to the class path. For example,
java -classpath "./libs/phone.jar;./libs/anotherlib.jar;./dialer.jar" com.company.dialer.DialerServer
or by editing the JAR manifest by adding "dependency JAR filess" to the manifest. Such a manifest file might look like:
Manifest-Version: 1.0
Class-Path: phone.jar anotherlib.jar
Build-Jdk-Spec: 1.8
Main-Class: com.company.dialer.DialerServer
or (if you are a developer having source code) you can use Maven to prepare a manifest for you by adding to the *.pom file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.company.dialer.DialerServer</mainClass>
<!-- Workaround for Maven bug #MJAR-156 (https://jira.codehaus.org/browse/MJAR-156) -->
<useUniqueVersions>false</useUniqueVersions>
</manifest>
</archive>
</configuration>
</plugin>
Please note that the above example uses ; as a delimiter in classpath (it is valid for the Windows platform). On Linux, replace ; by :.
For example,
java -classpath ./libs/phone.jar:./libs/anotherlib.jar:./dialer.jar
com.company.dialer.DialerServer

I'm developing an Eclipse based application also known as RCP (Rich Client Platform).
And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).
Cleaning the project and Maven update didn't help.
The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.

If you are using more than one module, you should have
dexOptions {
preDexLibraries = false
}
in your build file.

I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me (at least for me).
After hours of research, I found the following solution and it may help to Android developers who are doing development using Android Studio.
Modify the setting as below:
Preferences → Build, Execution, Deployment → Instant Run → *uncheck the first option.
With this change I am up and running.

My two cents in this chain:
Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.

Don't use test classes outside the module
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.

I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the Java rootloader. Because the different class loaders are in different security domains (according to Java) the JVM won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR 'java' ARGUMENTS]'
It produces output showing the loaded class, and the loader environment that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}

It happened to me in Android Studio.
The solution that worked for me: just restart Android Studio.

Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:
Firstly, create the instance of class in a simple thread and catch the crash.
Then call the field method of Class in main thread, you will get the NoClassDefFoundError.
Here is the test code:
public class MyClass{
private static Handler mHandler = new Handler();
public static int num = 0;
}
In your onCreate method of the Main activity, add the test code part:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test code start
new Thread(new Runnable() {
#Override
public void run() {
try {
MyClass myClass = new MyClass();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MyClass.num = 3;
// end of test code
}
There is a simple way to fix it using a handlerThread to the init handler:
private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}

One source of error for this exception could stem from inconsistent definitions for Proguard, e.g. a missing
-libraryJars "path.to.a.missing.jar.library".
This explains why compilation and running works fine, given that the JAR file is there, while clean and build fails. Remember to define the newly added JAR libraries in the ProGuard setup!
Note that error messages from ProGuard are really not up to standard, as they are easily confused with similar Ant messages arriving when the JAR file is not there at all. Only at the very bottom will there be a small hint of ProGuard in trouble. Hence, it is quite logical to start searching for traditional classpath errors, etc., but this will be in vain.
Evidently, the NoClassDefFound exception will be the results when running, e.g., the resulting executable JAR file built and based on a lack of ProGuard consistency. Some call it ProGuard "Hell".

I use the FileSync plugin for Eclipse, so I can live debug on Tomcat. I received NoClassFoundError, because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat, but I hadn't also added a folder sync for the extlib directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib

If you recently added multidex support in Android Studio like this:
// To support MultiDex
implementation 'com.android.support:multidex:1.0.1'
So your solution is just extend from MultiDexApplication instead of Application:
public class MyApp extends MultiDexApplication {

In my environment, I encountered this issue in a unit test. After appending one library dependency to *.pom, that's fixed.
Example:
Error message:
java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt
POM content:
<dependency>
<groupId>com.abc.def</groupId>
<artifactId>foo</artifactId>
<scope>test</scope>
</dependency>

I got this error after a Git branch change. For the specific case of Eclipse, there were missed lines in the .settings directory for the org.eclipse.wst.common.component file. As you can see below.
Restoring the project dependencies with Maven install would help.

If you are using gradlew, go to ./gradle/wrapper/gradle-wrapper.properties and change distributionUrl to the correct version of Gradle.
If you are using JDK14, try:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip

For Meteor or Cordova users,
It can be caused by the Java version you use. For Meteor and Cordova, stick with version 8 for now.
Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8
Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
Check if it is done
echo $JAVA_HOME
Go on and continue coding.

The Java 11 + Eclipse solution:
This solution is for you if you are not using module-info.java in your Eclipse project, and you added the JAR files manually instead of using Maven/Gradle.
Right click project → Build path → Configure build path → libraries tab
Remove the problematic JAR file from the modulepath
Add the JAR file to the classpath
More information is in
In Eclipse, what is the difference between modulepath and classpath?.

I deleted the folder "buid" and "out", and the IDE rebuild again this folders with updated content files.

Related

Spring Boot app throwing java.lang.NoClassDefFoundError: ch/qos/logback/classic/spi/ThrowableProxy [duplicate]

I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:
Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I think I might have the Main.java file in the wrong folder.
Here is the directory hierarchy:
graphics
├ Main.java
├ shapes
| ├ Square.java
| ├ Triangle.java
├ linepoint
| ├ Line.java
| ├ Point.java
├ spaceobjects
| ├ Cube.java
| ├ RectPrism.java
And here is Main.java:
import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;
public class Main {
public static void main(String args[]) {
Square s = new Square(2, 3, 15);
Line l = new Line(1, 5, 2, 3);
Cube c = new Cube(13, 32, 22);
}
}
What am I doing wrong here?
UPDATE
After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.
Really late UPDATE #2
I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.
After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader), which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use.
Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.
For example, if you had a class com.example.Foo, after compiling you would have a class file Foo.class. Say for example your working directory is .../project/. That class file must be placed in .../project/com/example, and you would set your classpath to .../project/.
Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.
I'd like to correct the perspective of others on NoClassDefFoundError.
NoClassDefFoundError can occur for multiple reasons like:
ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
Class file located, but Exception raised while initializing static variables
Class file located, Exception raised while initializing static blocks
In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes JAR file or to its package folder.
What does it mean by saying "available in compile time"?
The referenced class is used in the code. E.g.: Two classes, A and B (extends A). If B is referenced directly in the code, it is available at compile time, i.e., A a = new B();
What does it mean by saying "not available at compile time"?
The compile time class and runtime class are different, i.e., for example base class is loaded using classname of child class for example
Class.forName("classname")
E.g.: Two classes, A and B (extends A). Code has
A a = Class.forName("B").newInstance();
If you got one of these errors while compiling and running:
NoClassDefFoundError
Error: Could not find or load main class hello
Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- Solution -----------------------
The problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On compiling process, use this command:
javac -d . [FileName.java]
To run the class, please use this command:
java [Package].[ClassName]
NoClassDefFoundError means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime.
If you're using Eclipse, make sure you have the shapes, linepoints and the spaceobjects as entries in the .classpath file.
java.lang.NoClassDefFoundError
indicates that something was found at compile time, but not at run time. Maybe you just have to add it to the classpath.
NoClassDefFoundError in Java:
Definition:
NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:
Exception in thread "main" java.lang.NoClassDefFoundError
Possible Causes:
The class is not available in Java Classpath.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Any start-up script is overriding Classpath environment variable.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Possible Resolutions:
Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.
The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.
Resources:
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE
java.lang.NoClassDefFoundError – How to solve No Class Def Found Error
The no class definition exception occurs when the intended class is not found in the class path.
At compile time class: Class was generated from the Java compiler, but somehow at run time the dependent class is not found.
Let’s go through one simple example:
public class ClassA{
public static void main(String args[]){
// Some gibberish code...
String text = ClassB.getString();
System.out.println("Text is: " + text);
}
}
public class ClassB{
public static String getString(){
return "Testing some exception";
}
}
Now let's assume that the above two Java source code are placed in some folder, let's say "NoClassDefinationFoundExceptionDemo"
Now open a shell (assuming Java is already being set up correctly)
Go to folder "NoClassDefinationFoundExceptionDemo"
Compile Java source files
javac ClassB
javac ClassA
Both files are compiled successfully and generated class files in the same folder as ClassA.class and ClassB.class
Now since we are overriding ClassPath to the current working director, we execute the following command
java -cp . ClassA
and it worked successfully and you will see the output on the screen
Now let's say, you removed ClassB.class file from the present directory.
And now you execute the command again.
java -cp . ClassA Now it will greet you with NoClassDefFoundException. As ClassB which is a dependency for ClassA is not found in the classpath (i.e., the present working directory).
If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.
When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.
cd out
java -classpath . com.blahcode.Main
I have faced with the problem today. I have an Android project and after enabling multidex the project wouldn't start anymore.
The reason was that I had forgotten to call the specific multidex method that should be added to the Application class and invoked before everything else.
MultiDex.install(this);
Follow this tutorial to enable multidex correctly. https://developer.android.com/studio/build/multidex.html
You should add these lines to your Application class
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing NetBeans altogether and reopening the project there were no error reports.
This answer is specific to a java.lang.NoClassDefFoundError happening in a service:
My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.
However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.
The eventual solution: Restart the service!
It appears that the rpm upgrade invalidated the service's file handle on the underlying JAR file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.
For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved.
How did I discover the issue? Because I ran my project using the Selenium native Firefox driver with an old version of FF included with my application. I realized the problem was incompatibility between browser and driver.
Hope this can help anyone with a similar issue as mine, that generated this same Error Message.
If you are "starting" a class from a JAR file, make sure to start with the JAR full path. For example, (if your "main class" is not specified in Manifest):
java -classpath "./dialer.jar" com.company.dialer.DialerServer
And if there are any dependencies, such dependencies to other JAR files, you can solve such a dependency
either by adding such JAR files (full path to each JAR file) to the class path. For example,
java -classpath "./libs/phone.jar;./libs/anotherlib.jar;./dialer.jar" com.company.dialer.DialerServer
or by editing the JAR manifest by adding "dependency JAR filess" to the manifest. Such a manifest file might look like:
Manifest-Version: 1.0
Class-Path: phone.jar anotherlib.jar
Build-Jdk-Spec: 1.8
Main-Class: com.company.dialer.DialerServer
or (if you are a developer having source code) you can use Maven to prepare a manifest for you by adding to the *.pom file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.company.dialer.DialerServer</mainClass>
<!-- Workaround for Maven bug #MJAR-156 (https://jira.codehaus.org/browse/MJAR-156) -->
<useUniqueVersions>false</useUniqueVersions>
</manifest>
</archive>
</configuration>
</plugin>
Please note that the above example uses ; as a delimiter in classpath (it is valid for the Windows platform). On Linux, replace ; by :.
For example,
java -classpath ./libs/phone.jar:./libs/anotherlib.jar:./dialer.jar
com.company.dialer.DialerServer
I'm developing an Eclipse based application also known as RCP (Rich Client Platform).
And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).
Cleaning the project and Maven update didn't help.
The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.
If you are using more than one module, you should have
dexOptions {
preDexLibraries = false
}
in your build file.
I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me (at least for me).
After hours of research, I found the following solution and it may help to Android developers who are doing development using Android Studio.
Modify the setting as below:
Preferences → Build, Execution, Deployment → Instant Run → *uncheck the first option.
With this change I am up and running.
My two cents in this chain:
Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.
Don't use test classes outside the module
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the Java rootloader. Because the different class loaders are in different security domains (according to Java) the JVM won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR 'java' ARGUMENTS]'
It produces output showing the loaded class, and the loader environment that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
It happened to me in Android Studio.
The solution that worked for me: just restart Android Studio.
Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:
Firstly, create the instance of class in a simple thread and catch the crash.
Then call the field method of Class in main thread, you will get the NoClassDefFoundError.
Here is the test code:
public class MyClass{
private static Handler mHandler = new Handler();
public static int num = 0;
}
In your onCreate method of the Main activity, add the test code part:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test code start
new Thread(new Runnable() {
#Override
public void run() {
try {
MyClass myClass = new MyClass();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MyClass.num = 3;
// end of test code
}
There is a simple way to fix it using a handlerThread to the init handler:
private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}
One source of error for this exception could stem from inconsistent definitions for Proguard, e.g. a missing
-libraryJars "path.to.a.missing.jar.library".
This explains why compilation and running works fine, given that the JAR file is there, while clean and build fails. Remember to define the newly added JAR libraries in the ProGuard setup!
Note that error messages from ProGuard are really not up to standard, as they are easily confused with similar Ant messages arriving when the JAR file is not there at all. Only at the very bottom will there be a small hint of ProGuard in trouble. Hence, it is quite logical to start searching for traditional classpath errors, etc., but this will be in vain.
Evidently, the NoClassDefFound exception will be the results when running, e.g., the resulting executable JAR file built and based on a lack of ProGuard consistency. Some call it ProGuard "Hell".
I use the FileSync plugin for Eclipse, so I can live debug on Tomcat. I received NoClassFoundError, because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat, but I hadn't also added a folder sync for the extlib directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib
If you recently added multidex support in Android Studio like this:
// To support MultiDex
implementation 'com.android.support:multidex:1.0.1'
So your solution is just extend from MultiDexApplication instead of Application:
public class MyApp extends MultiDexApplication {
In my environment, I encountered this issue in a unit test. After appending one library dependency to *.pom, that's fixed.
Example:
Error message:
java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt
POM content:
<dependency>
<groupId>com.abc.def</groupId>
<artifactId>foo</artifactId>
<scope>test</scope>
</dependency>
I got this error after a Git branch change. For the specific case of Eclipse, there were missed lines in the .settings directory for the org.eclipse.wst.common.component file. As you can see below.
Restoring the project dependencies with Maven install would help.
If you are using gradlew, go to ./gradle/wrapper/gradle-wrapper.properties and change distributionUrl to the correct version of Gradle.
If you are using JDK14, try:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
For Meteor or Cordova users,
It can be caused by the Java version you use. For Meteor and Cordova, stick with version 8 for now.
Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8
Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
Check if it is done
echo $JAVA_HOME
Go on and continue coding.
The Java 11 + Eclipse solution:
This solution is for you if you are not using module-info.java in your Eclipse project, and you added the JAR files manually instead of using Maven/Gradle.
Right click project → Build path → Configure build path → libraries tab
Remove the problematic JAR file from the modulepath
Add the JAR file to the classpath
More information is in
In Eclipse, what is the difference between modulepath and classpath?.
I deleted the folder "buid" and "out", and the IDE rebuild again this folders with updated content files.

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: common/basicitems [duplicate]

I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:
Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I think I might have the Main.java file in the wrong folder.
Here is the directory hierarchy:
graphics
├ Main.java
├ shapes
| ├ Square.java
| ├ Triangle.java
├ linepoint
| ├ Line.java
| ├ Point.java
├ spaceobjects
| ├ Cube.java
| ├ RectPrism.java
And here is Main.java:
import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;
public class Main {
public static void main(String args[]) {
Square s = new Square(2, 3, 15);
Line l = new Line(1, 5, 2, 3);
Cube c = new Cube(13, 32, 22);
}
}
What am I doing wrong here?
UPDATE
After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.
Really late UPDATE #2
I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.
After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader), which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use.
Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.
For example, if you had a class com.example.Foo, after compiling you would have a class file Foo.class. Say for example your working directory is .../project/. That class file must be placed in .../project/com/example, and you would set your classpath to .../project/.
Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.
I'd like to correct the perspective of others on NoClassDefFoundError.
NoClassDefFoundError can occur for multiple reasons like:
ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
Class file located, but Exception raised while initializing static variables
Class file located, Exception raised while initializing static blocks
In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes JAR file or to its package folder.
What does it mean by saying "available in compile time"?
The referenced class is used in the code. E.g.: Two classes, A and B (extends A). If B is referenced directly in the code, it is available at compile time, i.e., A a = new B();
What does it mean by saying "not available at compile time"?
The compile time class and runtime class are different, i.e., for example base class is loaded using classname of child class for example
Class.forName("classname")
E.g.: Two classes, A and B (extends A). Code has
A a = Class.forName("B").newInstance();
If you got one of these errors while compiling and running:
NoClassDefFoundError
Error: Could not find or load main class hello
Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- Solution -----------------------
The problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On compiling process, use this command:
javac -d . [FileName.java]
To run the class, please use this command:
java [Package].[ClassName]
NoClassDefFoundError means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime.
If you're using Eclipse, make sure you have the shapes, linepoints and the spaceobjects as entries in the .classpath file.
java.lang.NoClassDefFoundError
indicates that something was found at compile time, but not at run time. Maybe you just have to add it to the classpath.
NoClassDefFoundError in Java:
Definition:
NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:
Exception in thread "main" java.lang.NoClassDefFoundError
Possible Causes:
The class is not available in Java Classpath.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Any start-up script is overriding Classpath environment variable.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Possible Resolutions:
Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.
The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.
Resources:
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE
java.lang.NoClassDefFoundError – How to solve No Class Def Found Error
The no class definition exception occurs when the intended class is not found in the class path.
At compile time class: Class was generated from the Java compiler, but somehow at run time the dependent class is not found.
Let’s go through one simple example:
public class ClassA{
public static void main(String args[]){
// Some gibberish code...
String text = ClassB.getString();
System.out.println("Text is: " + text);
}
}
public class ClassB{
public static String getString(){
return "Testing some exception";
}
}
Now let's assume that the above two Java source code are placed in some folder, let's say "NoClassDefinationFoundExceptionDemo"
Now open a shell (assuming Java is already being set up correctly)
Go to folder "NoClassDefinationFoundExceptionDemo"
Compile Java source files
javac ClassB
javac ClassA
Both files are compiled successfully and generated class files in the same folder as ClassA.class and ClassB.class
Now since we are overriding ClassPath to the current working director, we execute the following command
java -cp . ClassA
and it worked successfully and you will see the output on the screen
Now let's say, you removed ClassB.class file from the present directory.
And now you execute the command again.
java -cp . ClassA Now it will greet you with NoClassDefFoundException. As ClassB which is a dependency for ClassA is not found in the classpath (i.e., the present working directory).
If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.
When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.
cd out
java -classpath . com.blahcode.Main
I have faced with the problem today. I have an Android project and after enabling multidex the project wouldn't start anymore.
The reason was that I had forgotten to call the specific multidex method that should be added to the Application class and invoked before everything else.
MultiDex.install(this);
Follow this tutorial to enable multidex correctly. https://developer.android.com/studio/build/multidex.html
You should add these lines to your Application class
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing NetBeans altogether and reopening the project there were no error reports.
This answer is specific to a java.lang.NoClassDefFoundError happening in a service:
My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.
However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.
The eventual solution: Restart the service!
It appears that the rpm upgrade invalidated the service's file handle on the underlying JAR file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.
For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved.
How did I discover the issue? Because I ran my project using the Selenium native Firefox driver with an old version of FF included with my application. I realized the problem was incompatibility between browser and driver.
Hope this can help anyone with a similar issue as mine, that generated this same Error Message.
If you are "starting" a class from a JAR file, make sure to start with the JAR full path. For example, (if your "main class" is not specified in Manifest):
java -classpath "./dialer.jar" com.company.dialer.DialerServer
And if there are any dependencies, such dependencies to other JAR files, you can solve such a dependency
either by adding such JAR files (full path to each JAR file) to the class path. For example,
java -classpath "./libs/phone.jar;./libs/anotherlib.jar;./dialer.jar" com.company.dialer.DialerServer
or by editing the JAR manifest by adding "dependency JAR filess" to the manifest. Such a manifest file might look like:
Manifest-Version: 1.0
Class-Path: phone.jar anotherlib.jar
Build-Jdk-Spec: 1.8
Main-Class: com.company.dialer.DialerServer
or (if you are a developer having source code) you can use Maven to prepare a manifest for you by adding to the *.pom file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.company.dialer.DialerServer</mainClass>
<!-- Workaround for Maven bug #MJAR-156 (https://jira.codehaus.org/browse/MJAR-156) -->
<useUniqueVersions>false</useUniqueVersions>
</manifest>
</archive>
</configuration>
</plugin>
Please note that the above example uses ; as a delimiter in classpath (it is valid for the Windows platform). On Linux, replace ; by :.
For example,
java -classpath ./libs/phone.jar:./libs/anotherlib.jar:./dialer.jar
com.company.dialer.DialerServer
I'm developing an Eclipse based application also known as RCP (Rich Client Platform).
And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).
Cleaning the project and Maven update didn't help.
The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.
If you are using more than one module, you should have
dexOptions {
preDexLibraries = false
}
in your build file.
I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me (at least for me).
After hours of research, I found the following solution and it may help to Android developers who are doing development using Android Studio.
Modify the setting as below:
Preferences → Build, Execution, Deployment → Instant Run → *uncheck the first option.
With this change I am up and running.
My two cents in this chain:
Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.
Don't use test classes outside the module
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the Java rootloader. Because the different class loaders are in different security domains (according to Java) the JVM won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR 'java' ARGUMENTS]'
It produces output showing the loaded class, and the loader environment that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
It happened to me in Android Studio.
The solution that worked for me: just restart Android Studio.
Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:
Firstly, create the instance of class in a simple thread and catch the crash.
Then call the field method of Class in main thread, you will get the NoClassDefFoundError.
Here is the test code:
public class MyClass{
private static Handler mHandler = new Handler();
public static int num = 0;
}
In your onCreate method of the Main activity, add the test code part:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test code start
new Thread(new Runnable() {
#Override
public void run() {
try {
MyClass myClass = new MyClass();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MyClass.num = 3;
// end of test code
}
There is a simple way to fix it using a handlerThread to the init handler:
private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}
One source of error for this exception could stem from inconsistent definitions for Proguard, e.g. a missing
-libraryJars "path.to.a.missing.jar.library".
This explains why compilation and running works fine, given that the JAR file is there, while clean and build fails. Remember to define the newly added JAR libraries in the ProGuard setup!
Note that error messages from ProGuard are really not up to standard, as they are easily confused with similar Ant messages arriving when the JAR file is not there at all. Only at the very bottom will there be a small hint of ProGuard in trouble. Hence, it is quite logical to start searching for traditional classpath errors, etc., but this will be in vain.
Evidently, the NoClassDefFound exception will be the results when running, e.g., the resulting executable JAR file built and based on a lack of ProGuard consistency. Some call it ProGuard "Hell".
I use the FileSync plugin for Eclipse, so I can live debug on Tomcat. I received NoClassFoundError, because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat, but I hadn't also added a folder sync for the extlib directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib
If you recently added multidex support in Android Studio like this:
// To support MultiDex
implementation 'com.android.support:multidex:1.0.1'
So your solution is just extend from MultiDexApplication instead of Application:
public class MyApp extends MultiDexApplication {
In my environment, I encountered this issue in a unit test. After appending one library dependency to *.pom, that's fixed.
Example:
Error message:
java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt
POM content:
<dependency>
<groupId>com.abc.def</groupId>
<artifactId>foo</artifactId>
<scope>test</scope>
</dependency>
I got this error after a Git branch change. For the specific case of Eclipse, there were missed lines in the .settings directory for the org.eclipse.wst.common.component file. As you can see below.
Restoring the project dependencies with Maven install would help.
If you are using gradlew, go to ./gradle/wrapper/gradle-wrapper.properties and change distributionUrl to the correct version of Gradle.
If you are using JDK14, try:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
For Meteor or Cordova users,
It can be caused by the Java version you use. For Meteor and Cordova, stick with version 8 for now.
Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8
Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
Check if it is done
echo $JAVA_HOME
Go on and continue coding.
The Java 11 + Eclipse solution:
This solution is for you if you are not using module-info.java in your Eclipse project, and you added the JAR files manually instead of using Maven/Gradle.
Right click project → Build path → Configure build path → libraries tab
Remove the problematic JAR file from the modulepath
Add the JAR file to the classpath
More information is in
In Eclipse, what is the difference between modulepath and classpath?.
I deleted the folder "buid" and "out", and the IDE rebuild again this folders with updated content files.

java.lang.NoClassDefFoundError: org/apache/derby/jdbc/ClientDriver, have included derbyclient.jar in build path [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

my application crashing after successfully building [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

NoClassDefFoundError (initialization error) when i use JUNIT to test a class [duplicate]

I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:
Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I think I might have the Main.java file in the wrong folder.
Here is the directory hierarchy:
graphics
├ Main.java
├ shapes
| ├ Square.java
| ├ Triangle.java
├ linepoint
| ├ Line.java
| ├ Point.java
├ spaceobjects
| ├ Cube.java
| ├ RectPrism.java
And here is Main.java:
import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;
public class Main {
public static void main(String args[]) {
Square s = new Square(2, 3, 15);
Line l = new Line(1, 5, 2, 3);
Cube c = new Cube(13, 32, 22);
}
}
What am I doing wrong here?
UPDATE
After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.
Really late UPDATE #2
I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.
After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader), which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use.
Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.
For example, if you had a class com.example.Foo, after compiling you would have a class file Foo.class. Say for example your working directory is .../project/. That class file must be placed in .../project/com/example, and you would set your classpath to .../project/.
Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.
I'd like to correct the perspective of others on NoClassDefFoundError.
NoClassDefFoundError can occur for multiple reasons like:
ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
Class file located, but Exception raised while initializing static variables
Class file located, Exception raised while initializing static blocks
In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes JAR file or to its package folder.
What does it mean by saying "available in compile time"?
The referenced class is used in the code. E.g.: Two classes, A and B (extends A). If B is referenced directly in the code, it is available at compile time, i.e., A a = new B();
What does it mean by saying "not available at compile time"?
The compile time class and runtime class are different, i.e., for example base class is loaded using classname of child class for example
Class.forName("classname")
E.g.: Two classes, A and B (extends A). Code has
A a = Class.forName("B").newInstance();
If you got one of these errors while compiling and running:
NoClassDefFoundError
Error: Could not find or load main class hello
Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- Solution -----------------------
The problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On compiling process, use this command:
javac -d . [FileName.java]
To run the class, please use this command:
java [Package].[ClassName]
NoClassDefFoundError means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime.
If you're using Eclipse, make sure you have the shapes, linepoints and the spaceobjects as entries in the .classpath file.
java.lang.NoClassDefFoundError
indicates that something was found at compile time, but not at run time. Maybe you just have to add it to the classpath.
NoClassDefFoundError in Java:
Definition:
NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:
Exception in thread "main" java.lang.NoClassDefFoundError
Possible Causes:
The class is not available in Java Classpath.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Any start-up script is overriding Classpath environment variable.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Possible Resolutions:
Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.
The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.
Resources:
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE
java.lang.NoClassDefFoundError – How to solve No Class Def Found Error
The no class definition exception occurs when the intended class is not found in the class path.
At compile time class: Class was generated from the Java compiler, but somehow at run time the dependent class is not found.
Let’s go through one simple example:
public class ClassA{
public static void main(String args[]){
// Some gibberish code...
String text = ClassB.getString();
System.out.println("Text is: " + text);
}
}
public class ClassB{
public static String getString(){
return "Testing some exception";
}
}
Now let's assume that the above two Java source code are placed in some folder, let's say "NoClassDefinationFoundExceptionDemo"
Now open a shell (assuming Java is already being set up correctly)
Go to folder "NoClassDefinationFoundExceptionDemo"
Compile Java source files
javac ClassB
javac ClassA
Both files are compiled successfully and generated class files in the same folder as ClassA.class and ClassB.class
Now since we are overriding ClassPath to the current working director, we execute the following command
java -cp . ClassA
and it worked successfully and you will see the output on the screen
Now let's say, you removed ClassB.class file from the present directory.
And now you execute the command again.
java -cp . ClassA Now it will greet you with NoClassDefFoundException. As ClassB which is a dependency for ClassA is not found in the classpath (i.e., the present working directory).
If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.
When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.
cd out
java -classpath . com.blahcode.Main
I have faced with the problem today. I have an Android project and after enabling multidex the project wouldn't start anymore.
The reason was that I had forgotten to call the specific multidex method that should be added to the Application class and invoked before everything else.
MultiDex.install(this);
Follow this tutorial to enable multidex correctly. https://developer.android.com/studio/build/multidex.html
You should add these lines to your Application class
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing NetBeans altogether and reopening the project there were no error reports.
This answer is specific to a java.lang.NoClassDefFoundError happening in a service:
My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.
However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.
The eventual solution: Restart the service!
It appears that the rpm upgrade invalidated the service's file handle on the underlying JAR file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.
For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved.
How did I discover the issue? Because I ran my project using the Selenium native Firefox driver with an old version of FF included with my application. I realized the problem was incompatibility between browser and driver.
Hope this can help anyone with a similar issue as mine, that generated this same Error Message.
If you are "starting" a class from a JAR file, make sure to start with the JAR full path. For example, (if your "main class" is not specified in Manifest):
java -classpath "./dialer.jar" com.company.dialer.DialerServer
And if there are any dependencies, such dependencies to other JAR files, you can solve such a dependency
either by adding such JAR files (full path to each JAR file) to the class path. For example,
java -classpath "./libs/phone.jar;./libs/anotherlib.jar;./dialer.jar" com.company.dialer.DialerServer
or by editing the JAR manifest by adding "dependency JAR filess" to the manifest. Such a manifest file might look like:
Manifest-Version: 1.0
Class-Path: phone.jar anotherlib.jar
Build-Jdk-Spec: 1.8
Main-Class: com.company.dialer.DialerServer
or (if you are a developer having source code) you can use Maven to prepare a manifest for you by adding to the *.pom file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.company.dialer.DialerServer</mainClass>
<!-- Workaround for Maven bug #MJAR-156 (https://jira.codehaus.org/browse/MJAR-156) -->
<useUniqueVersions>false</useUniqueVersions>
</manifest>
</archive>
</configuration>
</plugin>
Please note that the above example uses ; as a delimiter in classpath (it is valid for the Windows platform). On Linux, replace ; by :.
For example,
java -classpath ./libs/phone.jar:./libs/anotherlib.jar:./dialer.jar
com.company.dialer.DialerServer
I'm developing an Eclipse based application also known as RCP (Rich Client Platform).
And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).
Cleaning the project and Maven update didn't help.
The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.
If you are using more than one module, you should have
dexOptions {
preDexLibraries = false
}
in your build file.
I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me (at least for me).
After hours of research, I found the following solution and it may help to Android developers who are doing development using Android Studio.
Modify the setting as below:
Preferences → Build, Execution, Deployment → Instant Run → *uncheck the first option.
With this change I am up and running.
My two cents in this chain:
Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.
Don't use test classes outside the module
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the Java rootloader. Because the different class loaders are in different security domains (according to Java) the JVM won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR 'java' ARGUMENTS]'
It produces output showing the loaded class, and the loader environment that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
It happened to me in Android Studio.
The solution that worked for me: just restart Android Studio.
Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:
Firstly, create the instance of class in a simple thread and catch the crash.
Then call the field method of Class in main thread, you will get the NoClassDefFoundError.
Here is the test code:
public class MyClass{
private static Handler mHandler = new Handler();
public static int num = 0;
}
In your onCreate method of the Main activity, add the test code part:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test code start
new Thread(new Runnable() {
#Override
public void run() {
try {
MyClass myClass = new MyClass();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MyClass.num = 3;
// end of test code
}
There is a simple way to fix it using a handlerThread to the init handler:
private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}
One source of error for this exception could stem from inconsistent definitions for Proguard, e.g. a missing
-libraryJars "path.to.a.missing.jar.library".
This explains why compilation and running works fine, given that the JAR file is there, while clean and build fails. Remember to define the newly added JAR libraries in the ProGuard setup!
Note that error messages from ProGuard are really not up to standard, as they are easily confused with similar Ant messages arriving when the JAR file is not there at all. Only at the very bottom will there be a small hint of ProGuard in trouble. Hence, it is quite logical to start searching for traditional classpath errors, etc., but this will be in vain.
Evidently, the NoClassDefFound exception will be the results when running, e.g., the resulting executable JAR file built and based on a lack of ProGuard consistency. Some call it ProGuard "Hell".
I use the FileSync plugin for Eclipse, so I can live debug on Tomcat. I received NoClassFoundError, because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat, but I hadn't also added a folder sync for the extlib directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib
If you recently added multidex support in Android Studio like this:
// To support MultiDex
implementation 'com.android.support:multidex:1.0.1'
So your solution is just extend from MultiDexApplication instead of Application:
public class MyApp extends MultiDexApplication {
In my environment, I encountered this issue in a unit test. After appending one library dependency to *.pom, that's fixed.
Example:
Error message:
java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt
POM content:
<dependency>
<groupId>com.abc.def</groupId>
<artifactId>foo</artifactId>
<scope>test</scope>
</dependency>
I got this error after a Git branch change. For the specific case of Eclipse, there were missed lines in the .settings directory for the org.eclipse.wst.common.component file. As you can see below.
Restoring the project dependencies with Maven install would help.
If you are using gradlew, go to ./gradle/wrapper/gradle-wrapper.properties and change distributionUrl to the correct version of Gradle.
If you are using JDK14, try:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
For Meteor or Cordova users,
It can be caused by the Java version you use. For Meteor and Cordova, stick with version 8 for now.
Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8
Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
Check if it is done
echo $JAVA_HOME
Go on and continue coding.
The Java 11 + Eclipse solution:
This solution is for you if you are not using module-info.java in your Eclipse project, and you added the JAR files manually instead of using Maven/Gradle.
Right click project → Build path → Configure build path → libraries tab
Remove the problematic JAR file from the modulepath
Add the JAR file to the classpath
More information is in
In Eclipse, what is the difference between modulepath and classpath?.
I deleted the folder "buid" and "out", and the IDE rebuild again this folders with updated content files.

Categories

Resources