A blog offering various X++ code snippets and tips for Microsoft Dynamics AX

Friday, July 25, 2008

Invoke a method at run time

Welcome to this lesson.

Through the Dict classes, AX allows you to invoke a particular method at run time.

This is useful if you want to call a different method based on some other condition which you do not know at design/compile time.


The following is a simple example:


static void invokeFindOnCustTable(Args _args)
{
  // Create an instance of dictTable passing a table as parameter
  DictTable dictTable = new DictTable(tableNum('CustTable'));
  CustTable customer;
  ;
  // Check if CustTable has method 'find'
  if (tableHasStaticMethod(dictTable, identifierstr('find')))
    // Invoke find method on CustTable at runtime
    customer = dictTable.callStatic(
      tableStaticMethodStr(CustTable, Find), '4000');

  info (customer.Name); // Displays Light and Design in AX 4 Demo Data
}


Here is another example which executes an object method on a class, if it exists:

static void invokeFindOnAClass(Args _args)
{
  // Table buffers
  SalesTable salesTable;

  // Objects
  SysDictClass dictClass;
  SalestableType salesTableType;
  ;
  dictClass = new SysDictClass(classNum('SalesTableType'));

  salesTable = SalesTable::find('00021_036');

  salesTableType = SalestableType::construct(salesTable);

  // If 'SalesTableType' has method delete
  if (dictClass.HasObjectMethod(identifierstr('delete')))
    // Invoke object method 'delete'
    // passing an object instance on which to execute the method
    dictClass.callObject('delete', salesTableType);
}


Code of this post currently tested on:

Dynamics AX 4.0
Dynamics AX 2009

If you any questions or comments e-mail me on: mirko@mirkobonello.com

No comments: