Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

jaxb2 - JaxB marhsalling using interfaces

I have the following class, i want to be able to produce xml dynamically based ona an interface, with changing implementations... is that possible... i have tried with little luck...

@xmlRootElement
public class Vehicles {
   private String id;

   private List<VehicleType> types;


   .... various setters and getters...
   ... with annotated getters...

}

public interface VehicleType {
   public String getName();
}

public Car implements VehicleType {

    private String name;
    private String wheels;

    ...various constructors...

    @XmlElement
    public String getName() {
      return name;
    }

    @XmlElement
    public String getWheels() {
      return wheels;
    }

 }

public Motorbike implements VehicleType {

    private String name;
    private String exhaust;

    ...various constructors...

    @XmlElement
    public String getName() {
      return name;
    }

    @XmlElement
    public String getExhaust() {
      return exhaust;
    }

 }

I want the marshlling of Vehicles to produce the following output:

<vehicles>
   <types>
     <car>
        ..car specific elements
     </car>
     <motorbike>
        .. mototrbike specific elements
     <motorbike>
   </types>
</vehicles> 

The vehicles class cannot know about the implementations, or which ones exist.. it only knows about the interface, which here im using as a marker interface really.. to allow me to populate a list with different implementations at runtime...

Is there anyway i can get jaxb be to render the output as xml with out the parent really knowing about the implementations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

The following will not work with the JAXB reference implementation but will work with EclipseLink JAXB (MOXy).

JAVA MODEL

Below is a simple domain model represented as interfaces. We will use the @XmlType annotation to specify a factory class to create concrete impls of these interfaces. This will be required to satisfy unmarshalling (see: http://blog.bdoughan.com/2011/06/jaxb-and-factory-methods.html).

Customer

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlType(
    propOrder={"name", "address"},
    factoryClass=Factory.class, 
    factoryMethod="createCustomer")
public interface Customer {

    String getName();
    void setName(String name);

    Address getAddress();
    void setAddress(Address address);

}

Address

import javax.xml.bind.annotation.XmlType;

@XmlType(factoryClass=Factory.class, factoryMethod="createAddress")
public interface Address {

    String getStreet();
    void setStreet(String street);

}

Factory

Below is the factory method that returns concrete impls of the interfaces. These are the impls that will be built during an unmarshal operation. To prevent requiring real classes I will leverage Proxy objects.

import java.lang.reflect.*;
import java.util.*;

public class Factory {

    public Customer createCustomer() {
        return createInstance(Customer.class);    }

    public Address createAddress() {
        return createInstance(Address.class);
    }

    private <T> T createInstance(Class<T> anInterface) {
        return (T) Proxy.newProxyInstance(anInterface.getClassLoader(), new Class[] {anInterface}, new InterfaceInvocationHandler());
    }

    private static class InterfaceInvocationHandler implements InvocationHandler {

        private Map<String, Object> values = new HashMap<String, Object>();

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            if(methodName.startsWith("get")) {
                return values.get(methodName.substring(3));
            } else {
                values.put(methodName.substring(3), args[0]);
                return null;
            }
        }

    }
}

jaxb.properties

To get this demo to work you will need to specify MOXy as your JAXB provider. This is done via a jaxb.properties file with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

DEMO CODE

In the demo code below we pass an arbitrary implementation of the interfaces to be marshalled.

Demo

import javax.xml.bind.*;

public class Demo {

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

        AddressImpl address = new AddressImpl();
        address.setStreet("123 A Street");

        CustomerImpl customer = new CustomerImpl();
        customer.setName("Jane Doe");
        customer.setAddress(address);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }

}

Output

Below is the output from running the demo code:

<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <name>Jane Doe</name>
   <address>
      <street>123 A Street</street>
   </address>
</customer>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...