JAXB静态编组与JAXBContext createMarshaller()

时间:2014-04-14 10:28:14

标签: java jaxb marshalling

我浪费了大量时间在下面的代码片段上,找出了放入jaxb.in​​dex的位置和内容,以及如何创建JAXBContext

JAXBContext jc = JAXBContext.newInstance(new Class[]{GenA.class, GenB.class, ...});
 // or
JAXBContext jc = JAXBContext.newInstance( "my.package.jaxb" );
Marshaller m = jc.createMarshaller(); 
OutputStream os = new FileOutputStream( "file.xml" );
m.marshal( object, os );

但是静态方法JAXB.marshal(object, "C:\\path\\file.xml");使它像人们期望的那样容易。

我读到创建JAXBContext资源非常紧张。为什么要使用第一种方法呢?静态方法的任何缺点?

1 个答案:

答案 0 :(得分:2)

JAXBContext表示用于将对象转换为XML或从XML转换对象的所有已处理元数据。由于它是线程安全的,您可以创建一次并重用它。与使用静态方法相比,这是一种性能提升。