簡體   English   中英

正確的創建JAXB對象的方法

[英]Proper way of creating JAXB objects

我注意到jaxb編譯器xjc生成的ObjectFactory類。 我讀了一些關於它的目的。

我想知道什么是創建jaxb對象的正確方法,因為我的目的我根本不需要這個類。 即使是普通的構造函數,我是否應該總是使用ObjectFactory ,或者我可以通過普通的構造函數構建對象(什么工作正常)?

編輯:添加示例:

我需要創建IpAddress實例

這是工廠方法:

  public IpAddress createIpAddress() {
        return new IpAddress();
    }

是不是更好IpAddress ia = new IpAddress()

要么

IpAddress ia = objectFactory.createIpdAddress()

如果使用ObjectFactory創建域對象的實例或僅使用JAXB 2(JSR-222)中的零arg構造函數,則創建的實例之間沒有區別。 JAXB 1(JSR-031)而不是POJO中,JAXB使用特定於供應商的impl類來創建創建的接口,然后需要ObjectFactory來創建實例。

有時候域對象需要包裝在JAXBElement的實例中, ObjectFactory包含執行此操作的有用方法(請參閱: http//blog.bdoughan.com/2012/07/jaxb-and-root-elements.html )。

JAXB最終需要ObjectFactory來包含它所包含的元數據。 在處理類時,JAXB將遍歷傳遞依賴項。 ObjectFactory上使用create方法提供了一個JAXB可以用來處理整個模型的元數據的類。


UPDATE

好。 那么最好的做法是什么才是正確的做法? (參見我的例子)

這真的取決於。 我個人更喜歡使用構造函數。 我在下面有一個例子來演示這兩種方法。

XML Schema

下面是我用來創建Java模型的XML Schema。

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
    <xs:element name="root" type="root"/>
    <xs:complexType name="root">
        <xs:sequence>
            <xs:element name="foo">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="bar" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

演示代碼

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

public class Demo {

    public static void main(String[] args) {
        // Using Constructors
        Root.Foo foo1 = new Root.Foo();
        foo1.setBar("Hello");
        Root root1 = new Root();
        root1.setFoo(foo1);
        JAXBElement<Root> jaxbElement1 = new JAXBElement<Root>(new QName("root"), Root.class, root1);


        // Using ObjectFactory
        ObjectFactory objectFactory = new ObjectFactory();
        Root.Foo foo2 = objectFactory.createRootFoo();
        foo2.setBar("World");
        Root root2 = objectFactory.createRoot();
        root2.setFoo(foo2);
        JAXBElement<Root> jaxbElement2 = objectFactory.createRoot(root2);
    }

}

JAXB使用ObjectFactory來標識要綁定的類,例如

    JAXBContext ctx = JAXBContext.newInstance("test"); <-- test is package
    Marshaller m = ctx.createMarshaller();
    m.marshal(new X(), System.out);  <-- X is test package

javax.xml.bind.JAXBException: "test" doesnt contain ObjectFactory.class or jaxb.index

JAXBContext ctx = JAXBContext.newInstance(X.class);
...

工作正常,因為我們明確地將X加載到JAXBCOntext

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM