简体   繁体   中英

Register Ecore meta-model programmatically

我使用转换引擎在运行时创建一个Ecore元模型,我想知道我们如何使用EMF注册该元模型,以便它可以识别元模型?

If you have the code generated by your metamodel:

resourceSet.getPackageRegistry()
  .put(org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage.eINSTANCE.getNsURI()
     , org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage.eINSTANCE);

(here for the "genmodel" metamodel)

If you only have the .ecore file:

// register globally the Ecore Resource Factory to the ".ecore" extension
// weird that we need to do this, but well...
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
    "ecore", new EcoreResourceFactoryImpl());

ResourceSet rs = new ResourceSetImpl();
// enable extended metadata
final ExtendedMetaData extendedMetaData = new BasicExtendedMetaData(rs.getPackageRegistry());
rs.getLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA,
    extendedMetaData);

Resource r = rs.getResource(uriOfYourModel, true);
EObject eObject = r.getContents().get(0);
if (eObject instanceof EPackage) {
    EPackage p = (EPackage)eObject;
    rs.getPackageRegistry().put(p.getNsURI(), p);
}

You can find a bit more about this code here with the method named registerEcorePackages() , used to register .ecore file in the workspace (with their workspace fullpath) in our custom package registry. If you want to register your metamodel in EMF global package registry, replace resourceSet.getPackageRegistry() by EPackage.Registry.INSTANCE .

I had to modify the code from @sbegaudeau a bit for it to work:

Replace

rs.getPackageRegistry().put(p.getNsURI(), p);

with

EPackage.Registry.INSTANCE.put(p.getNsURI(), p);

Also, somehow I cannot register the .ecore type. Had to use "*": Resource.Factory.Registry.INSTANCE. getExtensionToFactoryMap().put("*", new EcoreResourceFactoryImpl()); Resource.Factory.Registry.INSTANCE. getExtensionToFactoryMap().put("*", new EcoreResourceFactoryImpl());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM