CodexBloom - Programming Q&A Platform

Java 17: implementing JAXB and Module Path for XML Serialization

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-02
java jaxb xml java-17 modules Java

I'm working on a project and hit a roadblock. I'm sure I'm missing something obvious here, but I'm working with a question with JAXB when trying to serialize an object to XML in my Java 17 application that uses the module path. I'm getting a `javax.xml.bind.JAXBException: class "com.example.MyClass" does not have a JAXB-annotated element` behavior when I try to marshal my object. I have made sure that my class `MyClass` has the necessary JAXB annotations, but it seems like JAXB isn't recognizing them correctly. Here's the relevant part of my `MyClass`: ```java package com.example; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "myClass") public class MyClass { private String name; @XmlElement public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` I am using the following code to marshal the object: ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Main { public static void main(String[] args) throws Exception { MyClass myObject = new MyClass(); myObject.setName("Test Name"); JAXBContext context = JAXBContext.newInstance(MyClass.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(myObject, System.out); } } ``` I have also added the required JAXB dependencies in my `module-info.java`: ```java module my.module { requires java.xml.bind; exports com.example; } ``` I've tried cleaning and rebuilding the project multiple times, but the behavior continues. I suspect it might be related to how JAXB is being loaded in the module path since it worked fine in Java 8 without modules. How can I resolve this scenario? My development environment is Ubuntu. How would you solve this? I'm coming from a different tech stack and learning Java.