Jaxb API侦听器

时间:2013-12-11 19:21:59

标签: java jaxb eclipselink jaxb2

我创建了包含以下侦听器方法的Jaxb类,但只有unmarshall方法正在运行:

void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
        System.out.println("afterUnmarshal  1");
    }

    void beforeMarshal(Marshaller marshaller, Object parent) {
        System.out.println("beforeMarshal  2");
    }

    void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {
        System.out.println("beforeUnmarshal  3");
    }

    void afterMarshal(Marshaller marshaller, Object parent) {
        System.out.println("afterMarshal  4");
    }

OutPut:

beforeUnmarshal  3
afterUnmarshal  1

执行编组代码时不会调用marshall方法。


更新了问题: 问题: beforeMarshal Customer调用了两次。 OutPut:

afterUnmarshal  Address
afterUnmarshal  Customer
beforeMarshal  Customer
beforeMarshal  Customer
beforeMarshal  Address

计划:

 public class Demo {

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

            Unmarshaller u = jc.createUnmarshaller();
            File xml = new File("src/testRJE/input.xml");
            Customer customer = (Customer) u.unmarshal(xml);

            Marshaller m = jc.createMarshaller();
            m.marshal(customer, xml);
        }

    }


    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Customer {

      @XmlElementRef(name = "billing-address")
      @XmlJavaTypeAdapter(AddressAdapter.class)
      private Address address;

        public Address getAddress() {
            return address;
        }


        void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {//XML to Object
        System.out.println("afterUnmarshal  Customer");
    }

    void beforeMarshal(Marshaller marshaller ) {
        System.out.println("beforeMarshal  Customer");
    }

    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class Address {

        public Address() {
        }


        private String street;

        private String city;

      void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
        System.out.println("afterUnmarshal  Address");
    }

    void beforeMarshal(Marshaller marshaller ) {
        System.out.println("beforeMarshal  Address");
    }


    }

2 个答案:

答案 0 :(得分:2)

marshal事件方法不像unmarshal方法那样有Object参数。当您从方法签名中删除它们时,一切都应该按预期工作。

答案 1 :(得分:0)

显然,您已经扩展了只有方法afterUnmarshalbeforeUnmarshal的类Unmarshaller#Listener,这解释了为什么只调用这两个方法。

为了收听编组事件,你需要另一个监听器类扩展Marshaller#Listener,而这个类又有你需要的方法和你必须覆盖的方法。

另外,请注释使用注释@Override覆盖的方法。在课堂上完成此操作后,您应该会收到错误消息,指出课程Unmarshaller#Listener没有任何方法beforeMarshalafterMarshal