Tuesday, December 22, 2009

How to ignore Private, Protected and Abstract modifiers

I was always curious about the Best Practices messages "Implement static construct to allow for modifications." and "New should be protected."


Say, you want to create a new class derived from RunBaseBatch; if you follow the Best Practice warnings (as named above), your new()-method will be declared Protected. But how the Batch Framework can create an object from this class if the user decide to let that process run in batch mode?


Since the new()-method is protected, the object cannot created with that method, right? Theoretical yes, but do not underrate Reflection Technique in Dynamics AX.

As known, you can create objects and invoke methods on it, using an object of the kernel class DictClass (or its even more popular derivate SysDictClass). The DictClass object seems to be very powerful and follows its own rules of code execution abilities.

With a DictClass object you can create objects what theoretically not should be possible. Use the makeObject()-method and you can:
  • Create objects from classes which are abstract
  • Create objects from classes even the new()-method is declared as Private or Protected (the code execution really runs through the new()-method)
  • Create objects from classes which have not implemented all abstracted methods from the super class

But the power of the DictClass objects does not just end with creating other objects. You are also able to invoke:
  • Member and static methods despite protected, private or abstract modifier (callObject() and callStatic())

As if this wasn't enough, the DictTable object shares that behavior property too. You can invoke any table method you want by calling the callStatic()- or callObject()-method on the DictTable object.


You see, there are dirty tricks to leverage AX's code security and compiler checks. Even it is possible to do such things, I really recommend to avoid executing theoretical illegal operations as mentioned. This article just shows what is possible and not what make sense :)

(all content relates to AX 2009)

No comments:

Post a Comment