Question
How do I resolve the 'javax.xml.bind package does not exist' compilation error when using JAXB in Java 11?
try {
JAXBContext context = JAXBContext.newInstance("com.acme.foo");
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
FooObject fooObj = (FooObject) unmarshaller.unmarshal(new File("foo.xml"));
} catch (UnmarshalException ex) {
ex.printStackTrace();
} catch (JAXBException ex) {
ex.printStackTrace();
}
Answer
In Java 11, the Java EE modules, including JAXB (Java Architecture for XML Binding), have been removed from the standard Java SE environment, which leads to the 'javax.xml.bind package does not exist' error when compiling. Here's how to resolve it.
<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 11 no longer includes JAXB as part of the core Java libraries.
- The JAXB API was part of Java SE in earlier versions (like Java 8) but was moved to external libraries in Java 11.
- Using JAXB without the necessary dependencies will result in compilation errors.
Solutions
- Add the JAXB API as a dependency in your project. If you are using Maven, you can include it in your `pom.xml` file by adding the following dependency:
- Add the JAXB implementation to your project. For Maven, include this dependency in your `pom.xml`:
- For Gradle users, you can add the following dependencies in your `build.gradle` file:
- Ensure your IDE's project structure recognizes the added dependencies correctly, and refresh the project.
Common Mistakes
Mistake: Not including both JAXB API and its implementation in the dependencies.
Solution: Make sure to add both the JAXB API and the JAXB runtime implementation to your project dependencies.
Mistake: Forgetting to refresh the project after adding dependencies in the IDE.
Solution: After modifying `pom.xml` or `build.gradle`, ensure to refresh or rebuild your project in the IDE.
Helpers
- Java 11 JAXB
- javax.xml.bind package error
- fix JAXB error Java 11
- JAXB deserialization Java 11
- JAXB dependencies Maven
- Java XML binding error 2023