0

我正在编写一些 eclipse emf 代码,并想打印 EObject 的内容(而不是将其存储到磁盘)。

这是我尝试的:

  public static void print(EObject obj) {
    Resource eResource = obj.eResource();
    try {
      eResource.save(System.out, null);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

但这给出了 NullPointerException。我已经尝试过这个:

  public static void print(EObject obj) {
    ResourceSet resourceSet = new ResourceSetImpl();
    resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
        .put("*", new XMIResourceFactoryImpl());
    Resource resource = resourceSet.createResource(URI.createURI("dummyfile.xml"));
    resource.getContents().add(obj);
    try {
      resource.save(System.out, null);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

这行得通,但是如果不指定虚拟 URI 就不能打印到屏幕上吗?

4

2 回答 2

2

更新为包含 EcoreUtil.copy()

检查此代码。

Resource res = new XMLResourceImpl ();
res.getContents().add(EcoreUtil.copy(obj));
try {
  resource.save(System.out, null);
} catch (IOException ioe) {
  ioe.printStackTrace();
}

如果失败,那么是的,您需要一个虚拟 URI

Resource res = new XMLResourceImpl (URI.createURI("dummyfile.xml"));
res.getContents().add(EcoreUtil.copy(obj));
try {
  resource.save(System.out, null);
} catch (IOException ioe) {
  ioe.printStackTrace();
}
于 2011-01-09T19:14:44.717 回答
0

嗯,当我传递一份副本时:

Resource res = new XMLResourceImpl ();
res.getContents().add(ECoreUtil.copy(obj));
try {
  resource.save(System.out, null);
} catch (IOException ioe) {
  ioe.printStackTrace();
}

某些 xmi 属性未打印。但是,如果我多次调用上述方法并且不传递副本,我会得到 NullPointerException。我想我在这里不了解一些基本的 EMF/遏制功能?

所以我更新的问题是:

如果在以下代码中使用模型,是否可以在不修改内容的情况下打印 FULL EObject 模型?

于 2011-01-09T20:53:50.377 回答