Search code examples
code-generationemfxtend

Generate code from Metamodel via XTend


I have an Ecore model in an existing EMF project and want to print the name of all containing classes into a text file via XTend. How do you achieve this? The XTend examples don't show how to use a model and get Information out of it.


Solution

  • If you only need the EClasses of your Meta-Model then you can get them from your Model Package: YourEMFModelPackage.eINSTANCE.getEClassifiers() which returns a EList<EClassifier>. Since an EClass is an EClassifier you get all your EClass implementations org.eclipse.emf.ecore.impl.EClassImpl. For type-safety concerns you probably check if this List only contains EClasses, since all your EDataTypes are also EClassifier.

    So this should to the Trick: EcoreUtil.getObjectsByType(YourEMFModelPackage.eINSTANCE.getEClassifiers(), EcorePackage.eINSTANCE.getEClass())

    or:

    List<EClass> allEClasses = YourEMFModelPackage.eINSTANCE.getEClassifiers().stream().filter(p -> EClass.class.isInstance(p)).map(m -> EClass.class.cast(m)).collect(Collectors.toList());

    Update: If you don't have your Model-Code generated you're still able to do this, you only need to load your Ecore into a Resource:

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore",
                new EcoreResourceFactoryImpl());
        Resource resource = resourceSet.getResource(
                URI.createFileURI(
                        "../path/to/your/Ecore.ecore"),
                true);
        EPackage model = (EPackage) resource.getContents().get(0);
    

    If you have the EPackage then you get your EClass like mentioned above