How to access/call private/protected methods/variables in a class/table using reflection

Example of dummy class that implements private variable and method:
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):
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();
    }
}



 

Search

About

DaxOnline.org is free platform that allows you to quickly store and reuse snippets, notes, articles related to Dynamics AX.

Authors are allowed to set their own AdSense units.
Join us.

Blog Tags