What is JAXB and JAXB Example Code

I thought it may be nice for those googlers that want to know about JAXB, to have a quick working example to use.  So, that is the purpose of this post.

First off, what is JAXB?  Well, simply put, JAXB is for converting Java objects to XML or from XML to Java objects.  With the advent of Java 1.5, and annotations, this becomes extremely simple.

Download JAXB, dependencies to your local computer, and put them in a folder called “libs”. The dependencies JARs I have are…

  • activation-1.1.jar
  • jaxb-api-2.0.jar
  • jaxb-impl-2.0.5.jar
  • jsr173_api-1.0.jar

Copy the following Java source code to Employee.java, and proceed with the instructions below

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.*;
import java.io.StringReader;
import java.io.StringWriter;
 
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee
{
    public static void main(String args[]) throws JAXBException
    {
        final Employee john = new Employee();
        john.setId(1);
        john.setFirstName("John");
        john.setMiddleName("Robert");
        john.setLastName("Doe");
 
        // write it out as XML
        final JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
        StringWriter writer = new StringWriter();
        jaxbContext.createMarshaller().marshal(john, writer);
 
        // read it from XML
        final Employee johnRead =
            (Employee) jaxbContext.createUnmarshaller().unmarshal(
                new StringReader(writer.toString()));
        if (john.equals(johnRead))
        {   // write the new object out as XML again.
            writer = new StringWriter();
            jaxbContext.createMarshaller().marshal(johnRead, writer);
            System.out.println(
                "johnRead was identical to john: \n" + writer.toString());
        }
        else
        {
            System.out.println("john and johnRead are not equal");
        }
    }
 
    @XmlAttribute
    private int id;
 
    /**
     * Employee's first name
     */
    @XmlElement
    private
    String firstName;
 
    /**
     * Employee's middle name
     */
    @XmlElement
    private
    String middleName;
 
    /**
     * Employee's last name
     */
    @XmlElement
    private
    String lastName;
 
    public Employee()
    {
    }
 
    public int getId()
    {
        return id;
    }
 
    public void setId(int id)
    {
        this.id = id;
    }
 
    public String getLastName()
    {
        return lastName;
    }
 
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
 
    public String getMiddleName()
    {
        return middleName;
    }
 
    public void setMiddleName(String middleName)
    {
        this.middleName = middleName;
    }
 
    public String getFirstName()
    {
        return firstName;
    }
 
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
 
    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        Employee employee = (Employee) o;
 
        if (id != employee.id) return false;
        if (firstName != null ? !firstName.equals(employee.firstName) :
            employee.firstName != null) return false;
        if (lastName != null ? !lastName.equals(employee.lastName) :
            employee.lastName != null) return false;
        if (middleName != null ? !middleName.equals(employee.middleName) :
            employee.middleName != null) return false;
 
        return true;
    }
 
    @Override
    public int hashCode()
    {
        int result = id;
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (middleName != null ? middleName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;
    }
 
    @Override
    public String toString()
    {
        return "Employee{" +
            "id=" + id +
            ", firstName='" + firstName + '\'' +
            ", middleName='" + middleName + '\'' +
            ", lastName='" + lastName + '\'' +
            '}';
    }
}

The following commands will compile and run the source, if under a unix OS. If in windows, you’ll need to form your own classpath.

javac -classpath .:$(for jar in libs/*.jar; do echo -n "$jar:"; done) Employee.java
java -classpath .:$(for jar in libs/*.jar; do echo -n "$jar:"; done) Employee

The output should be as follows, but the XML will be on a single line…

johnRead was identical to john:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1">
 <firstName>John</firstName>
 <middleName>Robert</middleName>
 <lastName>Doe</lastName>
</employee>

42 Replies to “What is JAXB and JAXB Example Code”

  1. Great example. Thanks.

    Just a note: to make the marshaller output pretty printed XML, just add:

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  2. Thank you for making an example that didn’t include all the stuff with schema generation, class generation or the jaxb object factorys. My head was starting to hurt looking at all that stuff!!

  3. Hi Roben,

    JAXB is not a web service. It can be used in REST based web services, it is not a web service itself.

    But yes, that would be a good thing to blog about, if it’s not already easily found on google.

  4. pretty printed XML output:
    if (john.equals(johnRead))
    { // write the new object out as XML again.
    writer = new StringWriter();
    Marshaller marshaller =jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(johnRead, writer);

    System.out.println(“johnRead was identical to john: \n” + writer.toString());
    }
    else
    {
    System.out.println(“john and johnRead are not equal”);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *