By subclassing Marshaller.Listener abstract class, we can create listener class which will listen to marshling events. We can add our code if we want to perform some actions before and after marshalling. The Marshaller.Listener class has two methods which can be overridden. By default the methods doesn’t perform any actions.
1) public void beforeMarshal(Object source)
2) public void afterMarshal(Object source)
Where source represents the object being marshalled.
We set the listener class to the marshaller by calling the below methods
marshaller.setListener(new MarshalListener());
Main class
package JAXB;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBMarshalDemo3 {
public static void main(String[] args) throws JAXBException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setListener(new MarshalListener());
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ZipCode zipCode = new ZipCode();
zipCode.setPart1(1234);
zipCode.setPart2(5678);
Country country = new Country();
country.setCode(zipCode);
country.setName("India");
country.setPopulation(10000000);
File file = new File("result.xml");
FileWriter fw = new FileWriter(file);
marshaller.marshal(country, fw);
}
}
Listener
package JAXB;
import javax.xml.bind.Marshaller;
public class MarshalListener extends Marshaller.Listener {
@Override
public void beforeMarshal(Object source) {
super.beforeMarshal(source);
System.out.println("Before marshal: " + source.getClass().getName());
}
@Override
public void afterMarshal(Object source) {
super.afterMarshal(source);
System.out.println("After marshal: " + source.getClass().getName());
}
}
Output
Before marshal: JAXB.Country
Before marshal: JAXB.Country
Before marshal: JAXB.ZipCode
After marshal: JAXB.ZipCode
After marshal: JAXB.Country
After marshal: JAXB.Country