The infinite recursion is caused by the line 'obj.(propname) = val;' in setProp. This calls the SetMethod for the property 'propname'. When setting the value of a property, MATLAB checks to see if you are currently in the SetMethod for that property in order to avoid infinite recursion. However, since your SetMethod is an anonymous function which calls setProp (and not setProp itself), this assignment is not inside the SetMethod, and the assignment calls the anonymous function.
To avoid this issue, you may use a nested function as shown below:
classdef MyClass2 < dynamicprops
methods
function obj = MyClass2(propname, val)
P = obj.addprop(propname);
P.SetMethod = propSetFcn(obj, propname);
obj.(propname) = val;
end
end
end
function f = propSetFcn(obj, propname)
function setProp(obj, val)
obj.(propname) = val;
end
f = @setProp;
end
Best Answer