Adding extra methods to a JAXB class generated from schema

后端 未结 2 1189
无人共我
无人共我 2021-01-12 03:58

Here\'s a trivial excerpt from my XSD file




        
相关标签:
2条回答
  • 2021-01-12 04:42

    Following the link the Brian Henry gave, I found I could perform binding customization inline in my schema file to do what I wanted. The effect is exactly the same as Brian's solution, but it doesn't require a reference to a reference to com.sun.xml.internal.

    First, the schema file gets modified somewhat:

    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"
        xmlns:tns="sns" elementFormDefault="qualified"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    jaxb:version="2.0">
    
      <element name="document">
          <annotation>
              <appinfo>
                  <jaxb:class implClass="DocumentEx" />
              </appinfo>
          </annotation>
          <attribute name="title" use="required"/>
      </element>
    </schema>
    

    When the schema gets compiled into Java code, the generated ObjectFactory will refer to DocumentEx instead of Document. DocumentEx is a class I create, which looks like this:

    public class DocumentEx extends Document {
       public String getStrippedTitle() {
           return getTitle().replaceAll("\\s+", "");
       }
    }
    

    Document (the class I'm extending) is still generated by the schema-to-Java compiler. Now when I unmarshall a document I actually get a DocumentEx object:

        JAXBContext jaxbContext = JAXBContext.newInstance("com.example.xml");
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(testSchema);
        DocumentEx doc = (DocumentEx)unmarshaller.unmarshal(xmlFile);
    

    There is some (hard-to-parse) documentation for this at Oracle and some helpful examples at O'Reilly.

    0 讨论(0)
  • 2021-01-12 04:48

    You could try to update the property name you're seeing in the linked doc. try this instead:

    com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.FACTORY
    

    or

    "com.sun.xml.internal.bind.ObjectFactory"
    

    I'd guess that will get you past the PropertyException I figure you're seeing. The most thorough answer here, suggests this is not guaranteed to work, but worth trying since you've come this far. Source code, as far as I looked (not far) appears to support this property.

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