Accessing private\protected class methods and members from extension code AX7 (Dynamics 365 for Operations)

Hi,

Please follow below link

AX 7. Accessing private\protected class methods and members from extension code.

Reference

Reference

Example of dummy class that implements private variable and method:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class VKOReflectionBase
{
    private int privateVar;
 
    public void new()
    {
        privateVar      = 1;
    }
 
    public static void main(Args _args)
    {
        VKOReflectionBase reflectionTest;
 
        reflectionTest = new VKOReflectionBase();
 
        reflectionTest.run();
    }
 
    public void run()
    {
        this.someExtensionMethod();
        info(strFmt("private: %1", privateVar));
    }
 
    private int privateMethod(int _int, str _str)
    {
        info(strFmt("private method: %1-%2", _int, _str));
        return _int*2;
    }
}
Extension class (Same works for event handlers, just replace this with instance of object):
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Reflection;
 
[ExtensionOf(classStr(VKOReflectionBase))]
final class VKOReflectionBase_Extension
{
    public void setPrivateVar(int _newValue)
    {
        var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;
        var field = this.GetType().GetField(identifierStr(privateVar), bindFlags);
        // this can be any instantiated object
 
        if (field)
        {
            int localVar = field.GetValue(this); // getting value
            field.SetValue(this, _newValue); // setting value
        }
    }
 
    public void callPrivateMethod()
    {
        System.Object[] parametersArray = new System.Object[2]();
        parametersArray.SetValue(5, 0);
        parametersArray.SetValue('str', 1);
         
        var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;
  
        var methodInfo = this.GetType().GetMethod(methodStr(VKOReflectionBase, privateMethod), bindFlags);
  
        if (methodInfo)
        {
            int returnValue;
            returnValue = methodInfo.Invoke(this,  parametersArray);
            // Or use "new System.Object[0]()" instead of parametersArray if you do not have any parameters
        }
    }
 
    public void someExtensionMethod()
    {
        this.setPrivateVar(5);
        this.callPrivateMethod();
    }
}

Comments

Post a Comment