Question
How can I resolve the java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException when migrating from Java 8 to Java 9?
// Example JAXB usage
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
public class Example {
public static void main(String[] args) {
try {
JAXBContext context = JAXBContext.newInstance(YourClass.class);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Answer
The error `java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException` occurs when you attempt to use JAXB (Java Architecture for XML Binding) in Java 9 or newer. This is due to the removal of the JAXB API from the Java SE Platform, which was part of the JDK in earlier Java versions.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
Causes
- Java 9 introduced a modular system (Project Jigsaw) that removed certain Java EE APIs, including JAXB, from the standard JDK distribution.
- Lack of JAXB dependencies in your project when migrating to Java 9 or later, causing the application to fail at runtime.
Solutions
- Add the JAXB API dependency to your project. If you are using Maven, add the following dependency to your `pom.xml`:
- <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency>
- Include the implementation for JAXB usage in Maven. Add the following dependency to ensure the implementation is available: <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.1</version> </dependency>
- If you are not using Maven, you can download the JAXB implementation jars from a repository, like Maven Central, and include them in your project build path.
Common Mistakes
Mistake: Failing to add JAXB dependencies while upgrading the project to Java 9 or later.
Solution: Ensure that all required JAXB dependencies are included in the build configuration.
Mistake: Not recompiling the project after adding new dependencies.
Solution: Make sure to clean and rebuild the project to ensure all classes are compiled with the new dependencies.
Helpers
- java.lang.NoClassDefFoundError
- javax/xml/bind/JAXBException
- JAXB in Java 9
- JAXB error resolution
- Java 9 migration
- Maven JAXB dependency