EMF recursive subproperties

91 Views Asked by At

As you can see, the metamodel has a Test, which has properties. These can also have subproperties.

I want now to code a method, which gives back the properties as well as all other subproperties. Here is the naive approach without recursion. Please help me.

public EList<TestProperty> getProperties() {
        if (properties == null) {
            properties = new EObjectContainmentEList<TestProperty>(TestProperty.class, this,
                    Iec62264Package.TEST__PROPERTIES);
        }
        for (TestProperty property : properties) {
            properties.add(property.getSubProperties());
        }
        return properties;
    }

Metamodel

1

There are 1 best solutions below

0
On

Don't modify the basic generated EMF getters and setters. They are used by the EMF to persist your model, and it will introduce obvious problems.

You could add an EMethod getAllProperties, or an EReference allProperties with Derived=true. You will be able to give your specific implementation, and these kind of features are not involved in the EMF persistence.

So, keep your properties EReference, and its getProperties() getter as is, add a getAllProperties() EMethod, or allProperties derived EReference, and code it with something like :

/**
 * @generated
 */
public EList<TestProperty> getProperties() {
    if (properties == null) {
        properties = new EObjectContainmentEList<TestProperty>(TestProperty.class, this,
                Iec62264Package.TEST__PROPERTIES);
    }
    return properties;
}

/**
 * @generated NOT
 */
public EList<TestProperty> getAllProperties() {
    List<TestProperty> allProperties = new ArrayList<TestProperty>();
    for (TestProperty subProperty : getSubProperties()) {
        allProperties.add(subProperty);
        allProperties.addAll(subProperty.getAllProperties())
    }
    return allProperties;
}

And a method or derived EReference allProperties on the TestProperty EClass which returns all subproperties.

As an alternative, you could also use or get inspiration from the magic Xtext's EcoreUtil2.getAllContentsOfType(myTest, TestProperty.class) and implement your method with:

/**
 * @generated NOT
 */
public EList<TestProperty> getAllProperties() {
    return EcoreUtil2.getAllContentsOfType(this, TestProperty.class);
}