Get the variable values at runtime using reflection in Dlang

712 Views Asked by At

Is it possible to get the class/struct/other variables value during runtime in dlang to get/set its value? If yes how to do that please provide example. And also is it possible to get the runtime variable value?

Ex:

class S{ int svariable = 5;}
class B { int bvariable = 10;}
void printValue(T, T instanceVariable, string variableName) {
    writeln("Value of ",  variableName, "=", instanceVariable.variableName);
}

Output:

Value of svariable = 5;
Value of bvariable = 10;

2

There are 2 best solutions below

0
mitch_ On BEST ANSWER

There is a library named witchcraft that allows for runtime reflection. There are examples of how to use it on that page.

1
rcorre On

I'd first recommend trying a reflection library like @mitch_ mentioned. However, if you want to do without an external library, you can use getMember to get and set fields as well as invoke functions:

struct S {
    int i;
    int fun(int val) { return val * 2; }
}

unittest {
    S s;
    __traits(getMember, s, "i") = 5; // set a field
    assert(__traits(getMember, s, "i") == 5); // get a field
    assert(__traits(getMember, s, "fun")(12) == 24); // call a method
}