Load EMF Model instance in XTend

删除回忆录丶 提交于 2019-11-30 09:14:58

If you have an XMI and just want to generate code from it, you don't need Xtext at all. Just start with a Java project (I'd use a plug-in project, to reuse the dependency management) and start coding:

import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.EPackage
import org.eclipse.emf.ecore.resource.Resource$Factory$Registry
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl

class MyCodeGenerator {

  def static void main(String[] args) {
    new MyCodeGenerator().generate("mymodel.xmi")
  }

  def generate(String file) {
    doEMFSetup
    val resourceSet = new ResourceSetImpl
    val resource = resourceSet.getResource(URI.createURI(file), true)
    for (content : resource.contents) {
      generateCode(content)
    }
  }

  def dispatch generateCode(MySpecialType it) '''
    public class «name» {
      «FOR member : members»
      «ENDFOR»
    }
  '''

  def dispatch generateCode(MyMember it) '''
    private «type» «name»;
    ...
  '''

  def doEMFSetup() {
//    EPackage$Registry.INSTANCE.put(MyPackage.eINSTANCE.nsURI, MyPackage.eINSTANCE)
    Resource$Factory.Registry.INSTANCE.extensionToFactoryMap.put("xmi", new XMIResourceFactoryImpl);
  }

}

The dependencies you need to add to your Manifest :

Require-Bundle: org.eclipse.xtend.lib,
 com.google.guava,
 org.eclipse.xtext.xbase.lib,
 org.eclipse.emf.common,
 org.eclipse.emf.ecore,
 org.eclipse.emf.ecore.xmi
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!