Search your query

Friday, April 21, 2017

X++ Code to access Private / Protected methods and variables of AX class from Class extension (Get the table buffer value when extending the class).

Using System.Reflection;

We will not be able to access private / protected data member and methods of classes when you are going to create extension for them.

But there might be a situation to access those variables / methods from extension class. Reflection would be used in such this scenario.

Create an eventhandler extension class for VersioningPurchaseOrder -> and cosume PostConfirm method.

Using System.Reflection;

class VersioningPurchaseOrderEventHandlers
{
    /// <summary>
    /// accessing VersioningPurchaseOrder -> post_confirm method.
    /// </summary>
    /// <param name="args"></param>

    [PostHandlerFor(classStr(VersioningPurchaseOrder), methodStr(VersioningPurchaseOrder, confirm))]
    public static void VersioningPurchaseOrder_Post_confirm(XppPrePostArgs args)
    {
        VersioningPurchaseOrder   versioningPO;
        PurchTable                       purchTable;

        versioningPO = args.getThis();

        var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;

        var field = versioningPO.GetType().GetField("PurchTable", bindFlags);

        purchTable = field.getValue(versioningPO);

        if(purchTable)
        {
            info(purchTable.PurchId);
        }
    }

}

// We can also call / invoke the private / protected method(s) this VersioningPurchaseOrder class.

var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;

var createVersionMethod = versioningPO.GetType().GetMethod(methodStr(VersioningPurchaseOrder, createNewVersion), bindFlags);

if(createVersionMethod)
{
      createVersionMethod.Invoke(versioningPO , new System.Object[0]());
}

No comments:

Post a Comment