[英]Adding extra methods to a JAXB class generated from schema
這是我的XSD文件的一個簡單的摘錄
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"
xmlns:tns="sns" elementFormDefault="qualified">
<element name="document">
<attribute name="title" use="required"/>
</element>
</schema>
我使用maven-jaxb2-plugin
從中生成Java類。 Document
類有一個getTitle()
方法來返回title
屬性的文本。
我想為Document
添加一個額外的方法:
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
我希望我的額外方法出現在unmarshalled對象上(而不是我只是調用它或編寫一個包裝類)因為我想將頂級unmarshalled對象傳遞給一個字符串模板並讓它迭代調用我的子元素額外的方法。
我找到了說明,但是他們告訴我在Unmarshaller
上設置屬性,而我的(Mac OS X,Java 7)實現似乎不支持任何屬性。
我該怎么做?
在Brian Henry給出的鏈接之后,我發現我可以在我的模式文件中內聯綁定自定義來執行我想要的操作。 效果與Brian的解決方案完全相同,但它不需要引用com.sun.xml.internal
的引用。
首先,模式文件有所修改:
<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>
當模式編譯成Java代碼時,生成的ObjectFactory將引用DocumentEx
而不是Document
。 DocumentEx
是我創建的類,如下所示:
public class DocumentEx extends Document {
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
}
Document
(我正在擴展的類)仍然由schema-to-Java編譯器生成。 現在,當我解組文檔時,我實際上得到了一個DocumentEx對象:
JAXBContext jaxbContext = JAXBContext.newInstance("com.example.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(testSchema);
DocumentEx doc = (DocumentEx)unmarshaller.unmarshal(xmlFile);
您可以嘗試更新您在鏈接文檔中看到的屬性名稱。 試試這個:
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.FACTORY
要么
"com.sun.xml.internal.bind.ObjectFactory"
我想這會讓你超越我看到的PropertyException。 最完整的答案在這里 ,表明這是不能保證工作,但值得嘗試,因為你已經走到這一步。 源代碼,據我看(不遠)似乎支持這個屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.