As the title says: I wonder, whether it's possible to iterate through the object tree of an AnyLogic project.
Probably it would help, if I provide more information what I want to do. Take the following project tree:
I want to check for every delay object in my model, whether or not it currently contains agents. One possibility would be to add all delay objects manually to a collection object and to iterate through the elements of the collection. However, this approach would result in a lot of manual work, as I require to perform similar requests for other object types. In my opinion, the most convenient solution is to iterate through the project tree and to identify with 'isinstanceof' the objects I want to analyze.
Does anyone know a solution or another approach, which requires similar less effort?
Best regards,
Sebastian
You can loop through all objects in Main doing this:
for (Object currObject : ((Agent)getRootAgent()).getEmbeddedObjects()) {
if (currObject instanceof Delay) {
// you found a Delay object
}
}
Thanks you, I still have two questions:
1) I am pretty unfamiliar with Java and thought it's only possible to access properties and methds of an object with dot-syntax (i.e. object.property). It's the first time, I see something like this ((Agent)getRootAgent()). The brackets and the missing dot between Agent and getRootAgent confuses me. Can you explain me, how the underlying concept is called? I would like to know more.
2) With your approach, I am able to identify all delay objects. However, it's seems not possible to access the properties and attributes of the delay, for instance printing the name of the object with "System.out.print(currObject.getName())". An error message appears that the method getName() is undefined for the type Object. Any idea how to fix this?
re 1: This is called type-casting, normal Java capability.
re 2: Apply type-casting :) Something like "((Delay)currObject).getName()" should work