I want to retrieve the containments of an Ecore class. So I have for example a structure like this:
class SuperClass{
protected EObject superClassProperty;
}
class SubClass extends SuperClass{
private EObject subClassProperty;
}
Now I want to get all the containments of the SubClass (subClassProperty). I do it like this:
EList<EReference> _eAllContainments = eClass.getEAllContainments();
But if I do so I also get the inherited containments of the superclasses (superClassProperty). How can I just retrieve the ones that are contained in the given class (just subClassProperty)?
If you're refering to ecore, I assume that you're using EObject
elements.
Every EObject
implements the .eContents()
and the .eAllContents()
method.
The difference between them is:
.eContents()
gives you a List<EObject>
with all direct containment features (all features defined in the meta class with containment = true) of the Class it's called on.eAllContents()
gives you a TreeIterator<EObject>
with all containment features in a tree with your Class as root (basically it returns .eContents()
on all of the direct eContents()
wrapped into an iterator).So if you only want the values of the directly contained features then simply use eClass.eContents()
.
Because it is not completely clear to me what you're trying to achieve with:
EList<EReference>
= _eAllContainments = eClass.getEAllContainments();
I will show you some ways to use emf to get your desired Objects.
Assuming you have an Implementation Object of your Meta-Class (you should know the difference between Implementation and the meta-class, the meta-Class is the EClass
you're modeling and the Implementation is, well the Implemantion of this EClass
, but the EClass is a complete independent Object) then you get your meta-EClass of your Object by calling .eClass()
on it.
Every EClass
has information about its declared EReference
and its EAttribute
, you get them by calling eg: .getE[All]References()
, the .getAll...
also returns all Elements of the defined Super Classes of your EClass
.
So now you know how to get the meta-objects you defined, but how can you get the actual values representing them in your Implementation Object?
The answer is "reflection". EMF uses what is called reflective getter (.eGet
) and setter (.eSet
) , which take an EStructuralFeature
and return the actual value for it.
Because every EAttribute
and EReference
is an EStructuralFeature
you get the connection back from your EClass
information to your Implementation.
FYI: you can also get EStructuralFeatures of your EClass by name, then you could do something like that:
Supposing your element has an Attribute which is called name
then:
element.eGet(element.eClass().getEStructuralFeature("name"));
gives you the actual value for the attribute of your element.