java.lang.ClassNotFoundException – How to solve Class Not Found Exception (with video)
In this tutorial, we will discuss the java.lang.classnotfoundexception – ClassNotFoundException
. This exception is thrown when an application tries to load a class through its string name, but no definition for the specified class name could be found. A class can be loaded using one of the following methods:
- The
forName
method that resides inside theClass
class. - The
findSystemClass
method that resides inside theClassLoader
class. - The
loadClass
method that resides inside theClassLoader
class.
You can also check this tutorial in the following video:
This exception java.lang.classnotfoundexception extends the ReflectiveOperationException
, which is defined as the common superclass of exceptions thrown by reflective operations in core reflection. Finally, after the Java 1.4 release, the ClassNotFoundException
has been retrofitted to conform to the general purpose exception-chaining mechanism. The raising exception may be accessed via the Throwable.getCause()
method.
1. The java.lang.ClassNotFoundException in Java
The java.lang.ClassNotFoundException
is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. The Java ClassNotFoundException is a checked exception and thus, must be declared in a method or constructor’s throws clause.
The following example tries to load a class using the forName
method. However, the specified class name cannot be found and thus, a ClassNotFoundException
is thrown.
ClassNotFoundExceptionDemo.java
/** * @author Santosh Balgar Sachchidananda * This class tries to load MySQL driver. For the demo of ClassNotFoundexception * I haven't added the jar file in classpath. Add the mysql-connector jar in classpath * to fix this exception */ public class ClassNotFoundExceptionDemo { private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; public static void main(String[] args) throws Exception{ System.out.println("Trying to load MySQL JDBC driver"); Class.forName(DRIVER_CLASS); } }
A sample execution is shown below:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Class.java:315) at com.jcg.ClassNotFoundExceptionDemo.main(ClassNotFoundExceptionDemo.java:14)
To fix the exception download the mysql-connector
jar from Oracle website and include in your class path.
Above scenario is the most common scenario when CLassNotFoundException
is raised. However, it can become bit ugly or messy sometimes in a complex web deployment environments. Suppose your application is deployed as an EAR and it contains multiple jar and WAR files, it can sometimes raise this exception because of class visibility issues. Jar files and class files under EAR’s lib folder are visible to classes in WAR file, however jars and classes under war file’s lib folder can’t be seen by other modules or jars. It becomes even messier when different modules involved refer to different versions of same jar file. You need to be careful when such inter-dependencies exist.
2. How to deal with the java.lang.ClassNotFoundException
- Verify that the name of the requested class is correct and that the appropriate
.jar
file exists in your classpath. If not, you must explicitly add it to your application’s classpath. - In case the specified
.jar
file exists in your classpath then, your application’s classpath is getting overridden and you must find the exact classpath used by your application. - In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing
.jar
files in your classpath.
Below is the simple example to illustrate ClassNotFoundException
and a way to fix it.
MainClass
is dependent on DependentClass
for the successful execution, if everything is there as expected then you will see below output,
Hello from main class Loading dependent class Hello From Dependent Class Dependent class loaded successfully
For the demo purpose, I have removed DependentClass.class
from the output directory. Now if you try to run the MainClass
you get below output,
Hello from main class Loading dependent class Exception in thread "main" java.lang.NoClassDefFoundError: com/jcg/DependentClass at com.jcg.MainClass.main(MainClass.java:7) Caused by: java.lang.ClassNotFoundException: com.jcg.DependentClass at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 1 more
To fix this we need to make DependentClass.class
available. This can be done by rebuilding the project in our case. Otherwise you need to verify the classes and libraries in your class path and fix the same.
Below is the code for our example,
DependentClass.java
public class DependentClass { public void sayHello() { System.out.println("Hello From Dependent Class"); } }
MainClass.java
public class MainClass { public static void main(String[] args) { System.out.println("Hello from main class"); System.out.println("Loading dependent class"); DependentClass dClass = new DependentClass(); dClass.sayHello(); System.out.println("Dependent class loaded successfully"); } }
3. ClassNotFoundException vs NoClassDefFoundError vs UnSupportedClassVersionError
ClassNotFoundException
is generally thrown when you try to load a class using Class.forname
or loadClass
and findSytemClass
methods in ClassLoader
methods, the class you are trying to load is not present in the Classpath. Another scenario when it can happen is the class you are trying to load is not a valid class.
NoClassDefFoundError
is an error and it occurs when a class is present at compile-time and the same is missing at the run time. This is a fatal error and happens when you try to instantiate class or when you try to call a static method.
UnSupportedClassVersionEorror
this error happens when the class is compiled with a higher JDK version than the one used for execution. When you encounter this error, verify the installed Java version and the Java path set in the JAVA_HOME environment variable.
4. More articles
- java.lang.StackOverflowError – How to solve StackOverflowError
- Unreachable Statement Java Error – How to resolve it
- java.lang.NullPointerException Example – How to handle Java Null Pointer Exception (with video)
- Try Catch Java Example
- Java Constructor Example (with video)
- Online Java Compiler – What options are there
- What is null in Java
5. Download the source code
For the demo program, I have used IntelliJ Idea IDE and Java 11 version.
You can download the full source code of this example here: java.lang.ClassNotFoundException – How to solve Class Not Found Exception
Last updated on Jul. 23rd, 2021
I had the same problem with Kotlin
Problem: No entry in JDK Home (Eclipse / Windows / Preferences / Kotlin / Compiler)
Regards
FRAM