DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • How Does Video Annotation Augment Computer Vision?
  • Role of Data Annotation Services in AI-Powered Manufacturing
  • Annotating Data at Scale in Real Time
  • Filtering Java Collections via Annotation-Driven Introspection

Trending

  • The QA Paradox: To Save Artificial Intelligence, We Must Stop Blindly Trusting Data—And Start Trusting Human Judgment
  • Tracing Stratoshark’s Roots: From Packet Capture to System Call Analysis
  • Top 5 Trends in Big Data Quality and Governance in 2025
  • How My AI Agents Learned to Talk to Each Other With A2A
  1. DZone
  2. Coding
  3. Languages
  4. JAXB - No Annotations Required

JAXB - No Annotations Required

By 
Blaise Doughan user avatar
Blaise Doughan
·
Aug. 03, 12 · Interview
Likes (1)
Comment
Save
Tweet
Share
21.0K Views

Join the DZone community and get the full member experience.

Join For Free
There appears to be a misconception that annotations are required on the model in order to use a JAXB (JSR-222) implementation.  The truth is that JAXB is configuration by exception, so annotations are only required when you want to override default behaviour.  In this example I'll demonstrate how to use JAXB without providing any metadata.
 

Domain Model

I will use the following domain model for this example.   Note how there are no annotations of any kind.

Customer 

Customer is the root object in this example.  Normally we would annotate it with @XmlRootElement.  Later in the demo code you will see how we can use an instance of JAXBElement instead.
package blog.defaults;
 
import java.util.List;
 
public class Customer {
 
    private String firstName;
    private String lastName;
    private List<PhoneNumber> phoneNumbers;
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }
 
    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
 
}
 
PhoneNumber

I have purposefully given the fields in this class nonsense names, so that later when we look at the XML you will be able to see that by default the element names are derived from the properties and not the fields.
package blog.defaults;
 
public class PhoneNumber {
 
    private String foo;
    private String bar;
 
    public String getType() {
        return foo;
    }
 
    public void setType(String type) {
        this.foo = type;
    }
 
    public String getNumber() {
        return bar;
    }
 
    public void setNumber(String number) {
        this.bar = number;
    }
 
}

Demo Code

Since we haven't used @XmlRootElement (or @XmlElementDecl) to associate a root element with our Customer class we will need to tell JAXB what class we want to unmarshal the XML document to.  This is done by using one of the unmarshal methods that take a Class parameter (line 14).  This will return a JAXBElement, the Customer object is then accessed by calling getValue on it (line 15).  To marshal the object back to XML we need to ensure that it is wrapped in a JAXBElement to supply the root element information (line 17).

package blog.defaults;

import javax.xml.bind.*;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        StreamSource xml = new StreamSource("src/blog/defaults/input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class);
        Customer customer = je1.getValue();
 
        JAXBElement<Customer> je2 = new JAXBElement<Customer>(new QName("customer"), Customer.class, customer);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(je2, System.out);
     }

}

input.xml/Output

The following is the input to and output from running the demo code.  The first thing we see is that it is a very reasonable XML representation of the data, there aren't any JAXB artifacts. By default JAXB will marshal everything as XML elements, and based on our PhoneNumber class we see that the element names were derived from the property names.

<?xml version="1.0" encoding="UTF-8"?>
<customer> <firstName>Jane</firstName> <lastName>Doe</lastName> <phoneNumbers> <number>555-1111</number> <type>work</type>
</phoneNumbers>
<phoneNumbers> <number>555-2222</number>
<type>home</type> </phoneNumbers>
</customer>

Further Reading

If you enjoyed this post then you may also be interested in: 

  • The majority of the articles on this blog describe how to leverage the power of JAXB's metadata to support different use cases, I invite you to check them out: 
    • http://blog.bdoughan.com/search/label/JAXB
  • If you are interested in specifying metadata without using annotations, you may be interested in EclipseLink JAXB (MOXy)'s external mapping document:  
    • Extending JAXB - Representing Metadata as XML
    • Extending JAXB - Representing Metadata as JSON


Annotation

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Does Video Annotation Augment Computer Vision?
  • Role of Data Annotation Services in AI-Powered Manufacturing
  • Annotating Data at Scale in Real Time
  • Filtering Java Collections via Annotation-Driven Introspection

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: