The power of the TreeNode class

I though to revisit again a very powerful class you can use to generate dynamically objects, methods, set properties, etc. Basically, a somewhat reflection object in AX.

If you haven't used it before, just take a look at what you can do with it. It may help you at some point. Below is a small code snippet that can show you how simple it is and powerful at the same time:

public static void main(Args _a)
{
    #AOT
   
    TreeNode classes = TreeNode::findNode(#ClassesPath);
    TreeNode dynamicGenClass, dynamicGenMethod;
   
    str body = @" // generated
public void dynamicsGenerated()
{
    info ('dynamic generated');
}
    ";
   
    dynamicGenClass = classes.AOTadd('dynamicsGenClass');
   
    if (dynamicGenClass != null)
    {
        dynamicGenClass.AOTsave();
       
        dynamicGenMethod = dynamicGenClass.AOTadd('dynamicsGenerated');
        dynamicGenMethod.AOTsetSource(body);
       
        dynamicGenMethod.AOTsave();
       
        dynamicGenClass.AOTcompile();
    }
}


This code as you can observe will create a new class and a new method with the desired code. You can think you can do this task very very easy in the AOT yourself, and that is true. However, do not forgot that this can also be used to inspect properties of the objects, any property you can think of, as long as the property is visible in the AOT, so, include this in your bag of tricks.

No comments:

Post a Comment