Explain Codes LogoExplain Codes Logo

How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

java
no-class-def-found-error
jaxb
java-9
Alex KataevbyAlex Kataev·Oct 7, 2024
TLDR

To remove the java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException, add the JAXB API to your classpath.

For Maven:

<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency>

For Gradle:

implementation 'javax.xml.bind:jaxb-api:2.3.1'

That's it! They are the dependency configurations your project needs to work with JAXB classes for Java 9+!

Know your JAXB: An overview with Java 9+

JAXB was no longer included in Java 9, creating a gap for applications relying on it. To use it, you'll have to manually add it. In addition, remember to update package names from javax.xml.bind to jakarta.xml.bind after Java 11+.

For Java 9 & 10:

Set JVM flags to include JAXB:

--add-modules java.xml.bind

To add all EE modules:

--add-modules java.se.ee

Warning! This quick fix is not the best solution long-term.

For Java 11 and above

Instead, update your dependencies. Maven:

<dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.2</version> </dependency>

Gradle:

implementation 'jakarta.xml.bind:jakarta.xml.bind-api:2.3.2' implementation 'org.glassfish.jaxb:jaxb-runtime:2.3.2'

Remember, JAXB 2.3.1 made javax.activation obsolete. If you still need activation framework:

<dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>

Java 8 to 9+ seamless transition

When migrating from Java 8 to 9+, include an alternative JAXB provider such as EclipseLink MOXy to ease the migration process:

<dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.moxy</artifactId> <version>2.7.3</version> </dependency>

Then set a system property for the JAXB context factory:

-Djavax.xml.bind.JAXBContextFactory=org.eclipse.persistence.jaxb.JAXBContextFactory

Beware! Avoid deprecated com.sun classes and always use GlassFish's JAXB RI.

Staying ahead of Java's curve

Java offers new challenges and opportunities with each update. Review JEP 261 to understand Java's modularity system and its impact on your Java EE modules, including JAXB.

Java 9+ challenges may be around the corner but so are the sleek and efficient modular designs it intends to adopt. Strategise your migration and dependency management to not just address NoClassDefFoundError but also follow Java's new best practices.

Remember: explicit dependency management ensures compatibility with new Java releases as well as older versions!