What is a proper way of using reflection in AX?

Sometimes, when I need to do more complicated stuff than change one value in datasource, I would like some method on caller. For example I have a form A with overview. Form A has method setName() (I define). I open a related detail (form B). I change something and I want to call setName on caller.

Nowdays I am doing it in following way

element.args().caller().setName();

but I am looking for more idiomatic way. So what is proper way of calling method on caller?

Forms in AX are not types, so you can’t use any strongly-typed way. A better approach is using classes, passed in Args either as the caller or through parmObject(). If you do it in that way, it’s all simple. For example:

MyClass x = element.args().caller() as x;
if (x)
{
    x.setName(); // Compile-time control
}
else
{
    throw error(...);
}

If you’re using a form method, the compiler can’t verify whether it exists or not - you have to wait for code to fail at runtime, which may be quite risky. The only improvement you can do in that case is using formHasMethod() method and skipping the call if the method doesn’t exist (and potentially throwing a more descriptive error message).