A quick one for today.
Just had a question from someone on how to evaluate OCL from code. Assuming you have our Person class from the previous examples, place the following code in a button’s click event:
procedure TWinForm.Button1_Click(sender: System.Object; e: System.EventArgs);
var
OCLResult : IElement;
ObjList : IObjectList;
i : Integer;
begin
OCLResult := ECOSpace.OclService.EvaluateAndSubscribe(nil, ‘Person.AllInstances‘,
nil, nil);
if OCLResult is IObjectList then
begin
ObjList := IObjectList(OCLResult);
for i := 0 to ObjList.Count – 1 do
begin
MessageBox.Show(Person(ObjList.Item[i].AsObject).Firstname);
end;
end;
end;
Here, I’m executing some simple OCL (Person.AllInstances) and then iterating through the resulting collection. The Item property of IObjectList returns an IObject. You can then reference its AsObject method to get back a TObject, which you can cast as your Person and away you go.
Once you have your Person, dealing with any attributes or associations that it has will be much easier, as they will be correctly typed. It’s just "getting inside" our object model where we need to cast all over the shop.
Obviously, if your OCL doesn’t return a collection, then you’d deal differently, but the above code should get you started.
Be the first to leave a comment. Don’t be shy.