注:我是EclipseLink JAXB (MOXy)鉛和JAXB 2(JSR-222)專家組的成員。
查看以下EclipseLink示例。它演示瞭如何使用動態特性與JPA都和JAXB實現:
選項#1 - 帶有動態屬性靜態對象
莫西有一個@XmlVirtualAccessMethods
擴展名,它允許您將地圖中的條目映射到XML。這使您可以將屬性添加到靜態類。在下面的示例中,Customer類具有「真實」名稱屬性,並且可能具有許多「虛擬」屬性。
package blog.metadatasource.refresh;
import java.util.*;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlVirtualAccessMethods;
@XmlRootElement
@XmlType(propOrder={"firstName", "lastName", "address"})
@XmlVirtualAccessMethods
public class Customer {
private String name;
private Map<String, Object> extensions = new HashMap<String, Object>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object get(String key) {
return extensions.get(key);
}
public void set(String key, Object value) {
extensions.put(key, value);
}
}
虛擬屬性通過MOXy的XML元數據定義。在下面的例子中,我們將添加兩個屬性:middleName和shippingAddress。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="blog.metadatasource.refresh">
<java-types>
<java-type name="Customer">
<java-attributes>
<xml-element
java-attribute="middleName"
name="middle-name"
type="java.lang.String"/>
<xml-element
java-attribute="shippingAddress"
name="shipping-address"
type="blog.metadatasource.multiple.Address"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
更多信息
選項#2 - 動態對象
莫西也提供了完整的動態對象模型:
DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream, null, null, null);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
DynamicEntity customer = (DynamicEntity) unmarshaller.unmarshal(inputStream);
DynamicEntity address = jaxbContext.newDynamicEntity("org.example.Address");
address.set(street, "123 A Street");
address.set(city, "Any Town");
customer.set("address", address);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(customer, System.out);
更多信息
如果我得到你的權利,你可能有興趣在這兩個職位:http://stackoverflow.com/questions/4248099/jaxb-dynamically-generate-java-sources-without-xjc和http://stackoverflow.com/questions/4556179/how-to-force-schema-compiled-classes-to-extend-specific-class-outside-schema這是我如何從xml生成java類。 – Osw