代码之家  ›  专栏  ›  技术社区  ›  Shane C. Mason

如何制作JAXB对象的深度副本,如xmlbean XmlObject.copy()?

  •  2
  • Shane C. Mason  · 技术社区  · 17 年前

    我的任务是重构一些使用xmlbeans的组件,以利用jaxb。一切都进行得很顺利,直到我到达一个地方,前一位作者称之为 copy() function of one of the XmlObjects . 因为xmlbeans中的所有对象都扩展了XmlObject,所以我们免费获得了神奇的深度复制功能。

    4 回复  |  直到 17 年前
        1
  •  7
  •   Renganathan M G    11 年前

    你可以参考这个

    public static <T> T deepCopyJAXB(T object, Class<T> clazz) {
      try {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        JAXBElement<T> contentObject = new JAXBElement<T>(new QName(clazz.getSimpleName()), clazz, object);
        JAXBSource source = new JAXBSource(jaxbContext, contentObject);
        return jaxbContext.createUnmarshaller().unmarshal(source, clazz).getValue();
      } catch (JAXBException e) {
          throw new RuntimeException(e);
      }
    }
    
    public static <T> T deepCopyJAXB(T object) {
      if(object==null) throw new RuntimeException("Can't guess at class");
      return deepCopyJAXB(object, (Class<T>) object.getClass());
    }
    

    它对我有用。

    https://gist.github.com/darrend/821410

        2
  •  4
  •   Lukas Eder    13 年前

    您可以使用JAXBSource

    为同一类型创建2个JAXBContext:

    JAXBContext sourceJAXBContext = JAXBContext.newInstance("Foo.class");
    JAXBContext targetJAXBContext = JAXBContext.newInstance("Foo.class");
    

    然后做:

    targetJAXBContext.createUnmarshaller().unmarshal(
      new JAXBSource(sourceJAXBContext,sourceObject);
    
        3
  •  3
  •   Steve Kuo    17 年前

    Object obj = ...  // object to copy
    
    ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream());
    out.writeObject(obj);
    byte[] bytes = baos.toByteArray();
    
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
    Object copy = in.readObject();
    
        4
  •  3
  •   Lukas Eder    13 年前

    您可以使用XSD中的注释为生成的jaxb对象声明基类。。。

    <xsd:annotation>
      <xsd:appinfo>
        <jaxb:globalBindings>
          <xjc:superClass name="com.foo.types.support.JaxbBase" />
        </jaxb:globalBindings>
      </xsd:appinfo>
    </xsd:annotation>
    

    您可以使用xmlbeans基类作为模板添加可克隆性支持。