Set reference dynamically [message #1809564] |
Thu, 18 July 2019 09:33 |
Kai S. Messages: 20 Registered: June 2019 |
Junior Member |
|
|
Hey,
I am trying to set a reference feature after loading in an .ecore-model at runtime. Let's say my ecore-model defines 2 classes "Source" and "Target" and a reference "required" from "Source" to "Target" with the cardinality "0..*". So in the generated model code you have a member variable like this:
protected EList<Target> required;
Now, I create instance-objects dynamically of the classes "Source" and "Target". Lets say, both have an attribute "name" that I also set. So this would look like this:
//res here is the resource I loaded in dynamically from a given .ecore-file
EPackage metapackage = (EPackage) res.getContents().get(0);
EFactory metafactory = metapackage.getEFactoryInstance();
//creating an instance of SourceClass
EClass sourceClass = (EClass) metapackage.getEClassifier("SourceClass");
EAttribute sourceNameAttr = (EAttribute) sourceClass.getEStructuralFeature("name");
EObject sourceClassInstance = metafactory.create(sourceClass);
sourceClassInstance.eSet(sourceNameAttr, "Some beautiful source name...");
//creating an instance of TargetClass
EClass targetClass = (EClass) metapackage.getEClassifier("TargetClass");
EAttribute targetNameAttr = (EAttribute) targetClass.getEStructuralFeature("name");
EObject targetClassInstance = metafactory.create(targetClass);
targetClassInstance.eSet(targetNameAttr, "Some beautiful target name...");
Now, how do I set the "required"-reference from the sourceClassInstance to point to targetClassInstance? When looking at the documentation of EReference I do not find any setter-method to it, so I tried something like the following:
for(EReference r: sourceClass.getEAllReferences()) {
if(r.getName().contentEquals("required")) {
sourceClassInstance.eSet(r, targetClassInstance);
}
}
But this does not seem to work.
Does anyone know how I would go about setting the "required"-reference to point to the targetClassInstance? Since this a 0..*-reference and thus implemented as a list, do I somehow need to retrieve the list and then call add() on it?
Thanks a lot!
|
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.03195 seconds