EMF在运行时从ECore XMI生成模型类

时间:2012-12-08 15:06:52

标签: eclipse eclipse-emf eclipse-emf-ecore

据我所知,我们可以像这样生成ECore模型:

// 动态创建一个Book的子类,Magic power comes from here
        // create the SchoolBook EClass
        EClass schoolBookEClass = efactory.createEClass();
        schoolBookEClass.setName("SchoolBook");

        // create a new attribute for this EClass
        EAttribute level = efactory.createEAttribute();
        level.setName("level");
        level.setEType(epackage.getEInt());
        schoolBookEClass.getEStructuralFeatures().add(level);

        // 设置父类
        schoolBookEClass.getESuperTypes().add(ExtlibraryPackage.eINSTANCE.getBook());

        // 创建新的课程类
        EClass courseEClass = efactory.createEClass();
        courseEClass.setName("Course");

        // 课程名称属性
        EAttribute courseName = efactory.createEAttribute();
        courseName.setName("courseName");
        courseName.setEType(epackage.getEString());
        courseEClass.getEStructuralFeatures().add(courseName);

        // 课程对教材的引用关系
        EReference courseBook = efactory.createEReference();
        courseBook.setName("courseBook");
        courseBook.setEType(schoolBookEClass);
        courseBook.setContainment(false);
        courseEClass.getEStructuralFeatures().add(courseBook);

        // 创建包
        EPackage schoolPackage = efactory.createEPackage();
        schoolPackage.setName("elv");
        schoolPackage.setNsPrefix("elv");
        schoolPackage.setNsURI("http:///www.elver.org/School");
        schoolPackage.getEClassifiers().add(courseEClass);
        schoolPackage.getEClassifiers().add(schoolBookEClass);
        EPackage.Registry.INSTANCE.put(schoolPackage.getNsURI(), schoolPackage);

在类路径中根本没有这样的类,但我们可以将它们用于其他操作,创建ui,例如保存到数据库。

如果我在xml文件中定义了一些EMF模型类(例如mymodel.ecore),它只包含那些ECore模型的XMI序列化。那么如何在运行时创建它们的实例而不在类路径上生成类。

1 个答案:

答案 0 :(得分:1)

您实际上可以在运行时加载ECore模型并实例化对象:

    ResourceSet resourceSet = new ResourceSetImpl();
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( "ecore", new EcoreResourceFactoryImpl());
    Resource resource = resourceSet.getResource(URI.createFileURI("C:\\my.ecore"), true);
    EPackage model = (EPackage)resource.getContents().get(0);
    EClass eClass = (EClass) model.getEClassifiers().get(0);
    EObject object = model.getEFactoryInstance().create(eClass);