I’m currently working on code implementation that involves using JAXB for unmarshalling. Just an example of what my XML data looks like:
<services> <service type="0">...</service> <service type="1">...</service> <service type="1">...</service> </services>
I’m unmarshalling this to Object Services.java
having List<Service>
. Each service has common data like name, status, type (the attribute) and along with their own service specific data. To represent type I have created an enum Type.java
.
public enum Type { FILE("0","File"){ @Override public Service createServiceInstance(ServiceAttributes attributes){ return FileService.createInstance(attributes); } }, NETWORK("1","Network"){ // overridden createServiceInstance method } // declaration of string type variables for typeCode and typeName // constructor declaration with two arguments typeCode and typeName public abstract Service createServiceInstance(ServiceAttribtes attributes); } public class Service { //declaration of variables representing common data; private Type type; // getters and setters }
I have created one class for each of the service that extends the Service.java
and having variables representing data specific to that service. An example is as below :
public class NetworkService extends Service { private Link link; // getters and setters public static Service createInstance(ServiceAttributes attributes) { NetworkService ns = new NetworkService(); ns.setName(attributes.getName()); ns.setType(attributes.getType()) ns.setLink(attributes.getLink()) return ns; } }
To aid the unmarshalling process, I have created a class that extends the XmlAdapter :
public class ServiceTypeAdapter extends XmlAdapter<ServiceTypeAdapter.ServiceAttributes, Service> { public ServiceAttributes marshal(Service service) throws Exception { // currently I need only the unmarshalling method // And I know this will never be required. What should I do here? // return null or throw new UnsupportedOperationException() ? return null; } public Service unmarshal(ServiceAttributes serviceAttributes) { Type serviceType = serviceAttributes.getType(); return serviceType.createServiceInstance(serviceAttributes); } public class ServiceAttributes { private String name; @XmlAttribute private Type type; // declaration of attributes that will be present in // each of service classes // getters and setters } }