How do I resolve ClassNotFoundException?
Quickly defuse the ClassNotFoundException
by adjusting classpath visibility:
- Ensure the class's JAR is present—Build Path for IDEs or incorporate with
-cp
flag for command line users: - For web apps, JARs need to reside in the server's
WEB-INF/lib
. - Always remember to recompile your Java project post modifications.
Introduction to classpath
A classpath is the JVM parameter used to specify locations (directories or JARs) from where Java classes can be fetched. The frustrating ClassNotFoundException
usually rears its head when the JVM can't locate a class referenced in your code within the defined classpaths.
Classpath details
Some essentials with classpath to combat issues:
- Set classpath: Use
java -cp
or your IDE settings to define a comprehensive list of directories and JAR files. - Check paths: Confirm each class or JAR file path specified in the classpath is accurate, accessible, and appropriately named.
- Include ‘.’ or ‘./’: To cover classes without packages.
Maven and dependency conflicts
Working with Maven? MethodInvocation of ClassNotFoundException
could hint at conflicting dependencies:
Fix the brawl: Ensure your pom.xml
defines the correct versions of dependencies fighting over supremacy.
Eclipse: Update classpath
Eclipse makes managing classpath a breeze:
- Project Properties: Right-click, choose
Properties
. - Java Build Path: Look under
Libraries
. - Add JARs/classes: Click on
Add JARs
orAdd External JARs
.
Tweaking launch configuration
Java applications and their setup often dictate how to outfox ClassNotFoundException
:
- Console apps: Alter
-cp
argument orClass-Path
entry inMANIFEST.MF
. - Eclipse games: classpath can be modified under project's Run Configurations.
Pre-execution checks
Before launching, verify your main class's name, title, and structure. A mix-up here can make your JVM throw a tantrum in the form of ClassNotFoundException
, and we don't want that.
OS nuances in classpath
Defining classpath in terminal or script? Use OS specific path delimiter (;
for Windows, :
for Linux/macOS):
Was this article helpful?