Thursday, May 15, 2008

Removing an EMF object from an EMF generated model

The toughest part so far i have worked with is removing an EMF object.
I have an EMF generated model and I want to remove an element(object) from the model.
To my surprise all the methods in EObject are returning read only properties and when i try to remove an element from an Eobjects object, in runtime iam getting UNSUPPORTEDTYPEEXCEPTION which is trivial coz all the methods are returning read only elements/lists....
Then I did a sample test... i want to remove "emfObjectToBeRemoved" from "emfParentObject".

EList originalList = emfParentObject.eContents(); // returns a readonly list
List duplicateList = new ArrayList();
duplciateList.addAll(originalList); //line 3 , copying the list
duplicateList.remove(emfObjectToBeRemoved); // line 4

To my shock duplicateList is removing properly but the element is not getting removed from originalList...
I broke my head for some hours, did some googling and i dint have any clue ...Then when i was about to leave office , I felt like googling again and this time miracle happened...I observed an open bug with subject EcoreUtil.remove(object) in Eclipse Bugzilla and for a minute i was surprised seeing that EcoreUtil. I wasnt aware of that.

Then after line 4 , I put this statement

and when i run it , it is able to delete from EMF model(original list) also .....
I hope poor ppl like me will make use of this tip and merry ...

If you have an alternative for this, plz add it in comments..


mark le said...

Thanks for your great tip. Made my day.

Hal Esk said...

Thanks a lot!