JAXBContext.newInstance variations

前端 未结 1 635
情书的邮戳
情书的邮戳 2020-12-30 01:00

I am experimenting with the various forms of newInstance method in class JAXBContext (I am using the default Sun JAXB implementation that s

相关标签:
1条回答
  • 2020-12-30 01:45

    JAXB Model Generated from XML Schema

    When creating a JAXBContext from a model generated from an XML schema I always recommend doing it on the package name of the generated classes.

    JAXBContext jc = JAXBContext.newInstance("example.a");
    

    It is even better to use a newInstance method that takes a ClassLoader parameter. This will save you grief when you move from a Java SE to Java EE environment.

    JAXBContext jc = JAXBContext.newInstance("example.a", example.a.ObjectFactory.class.getClassLoader());
    

    When you create the JAXBContext on the package name, the JAXB impl assumes you generated the model from an XML schema and pulls in the ObjectFactory class since it always generates the class annotated with @XmlRegistry with this name.

    Starting from a Java Model

    This is when I recommend people use the newInstance methods that take classes. When bootstrapping a JAXBContext from JAXB classes there is nothing special about a class called ObjectFactory. The role of the ObjectFactory could be played by any class annotated with @XmlRegistry so it is not automatically looked for. This is why your use case worked when you explictly reference ObjectFactory and failed when you did not.

    0 讨论(0)
提交回复
热议问题