【发布时间】:2019-11-29 04:19:08
【问题描述】:
我正在内存中动态创建 Ecore 模型的实例,将其序列化为 XMI,然后用户可能会在我的应用程序运行时对其进行修改。所以我然后反序列化 XMI 并将它与我仍然在内存中的先前模型版本进行比较。
这样做时,我模型中的包含引用似乎丢失了。假设底层 Ecore-Model 如下所示:它有一个类 State 和一个类 Transition,而 Transition 通过名为 transition 的包含引用包含在 State 中,基数为 0..* .因此,模型实例的简单序列化 XMI 可能如下所示:
<?xml version="1.0" encoding="ASCII"?>
<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:designmodel="http://www.example.org/designmodel">
<designmodel:State xmi:id="0f359d4a-5154-462c-90aa-e125197cdb6d" name="Ready">
<transition href="#7880aa8f-1e86-42e0-a212-e91326292d31"/>
</designmodel:State>
<designmodel:Transition xmi:id="7880aa8f-1e86-42e0-a212-e91326292d31" name="switchToWaiting"/>
</xmi:XMI>
现在,当检查我在内存中的模型版本时,一切都符合预期,并且在 Transition-object 上调用 eContainer() 返回它包含的相应 State-object。但是当对反序列化的 XMI 模型执行相同操作时-实例,eContainer() 返回 NULL。
当单步调试调试器并查看各自的XMIResource 对象时,我可以看到相同的结果:对于反序列化的 XMIResource 的 Transition-object,eContainer-property 为 NULL,但为我保留在内存中的那个设置正确。
所以看起来容器在序列化/反序列化过程中丢失了。我的序列化看起来像这样:
ResourceSet savingResSet = new ResourceSetImpl();
savingResSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
XMIResource savingRes = (XMIResource) savingResSet.createResource(URI.createFileURI(outputPath), null);
savingRes.getDefaultSaveOptions().put(XMIResource.OPTION_KEEP_DEFAULT_CONTENT, Boolean.TRUE);
//adding the generated elements to the resource
generatedDesignmodelElements().forEach(e -> {
if(e != null) {
savingRes.getContents().add(e);
savingRes.setID(e, UUID.randomUUID().toString());
}
});
//saving it
try {
savingRes.save(Collections.EMPTY_MAP);
} catch (IOException e) {
e.printStackTrace();
反序列化就这么简单:
ResourceSet resSet = new ResourceSetImpl();
resSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
XMIResource updatedModel =(XMIResource)resSet.getResource(URI.createFileURI(sourcePath), true);
//iterating over the objects directly contained in the resource (so all State- and Transition-objects get reached here, since they are root objects themselves)
updatedModel.getContents().forEach(updatedModelElement -> {
System.out.println(updatedModelelement + updatedModelElement.eContainer()); //this is always NULL
});
那么:为什么这个eContainer()-call 总是为我反序列化的 XMIResource 返回 NULL,但在我在内存中的 XMIResource 上调用时表现正常?
非常感谢:)
【问题讨论】:
标签: java deserialization emf eclipse-emf ecore