如您所见,元模型具有一个Test,该Test具有属性。这些也可以具有子属性。
我现在想编写一个方法,该方法可以返回属性以及所有其他子属性。这是没有递归的幼稚方法。请帮我。
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;
}
不要修改基本的生成的EMF获取器和设置器。 EMF使用它们来持久化您的模型,这会带来明显的问题。
您可以添加EMethod getAllProperties或具有Derived = true的EReference allProperties。您将能够提供自己的特定实现,并且EMF持久性不涉及这些功能。
因此,请保持属性EReference及其getProperties()的getter不变,添加一个getAllProperties()EMethod或allProperties派生的EReference,并使用类似::>的代码
/** * @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; }
以及返回所有子属性的TestProperty EClass上的方法或派生的EReference allProperty。
作为替代,您还可以使用魔术Xtext的EcoreUtil2.getAllContentsOfType(myTest,TestProperty.class)或从中获得启发,并通过以下方法实现您的方法:
/**
* @generated NOT
*/
public EList<TestProperty> getAllProperties() {
return EcoreUtil2.getAllContentsOfType(this, TestProperty.class);
}