MATLAB: How to keep the SetMethod and GetMethod of the dynamic properties when saving and loading the class instance in MATLAB R2019a

MATLABoop

I have a class with dynamic properties. These properties are added on-the-fly. But when I save and load a class instance the GetMethod and SetMethod are not set anymore. How can I keep my GetMethod and SetMethod?

Best Answer

You need to implement your own saveobj and loadobj. In the saveobj you convert your class instance into a struct and store some meta information about your dynamic properties. In the loadobj you convert the previously created struct back into your class instance. See the example below:
classdef myCls < dynamicprops
properties
Prop1
Prop2
end
methods
function s = saveobj(obj)
s.Prop1 = obj.Prop1;
s.Prop2 = obj.Prop2;
dynPropNames = setdiff(properties(obj), {'Prop1' 'Prop2'});
for i=numel(dynPropNames):-1:1
p = findprop(obj, char(dynPropNames(i)));
s.DynPropInfo(i).Name = p.Name;
s.DynPropInfo(i).Value = obj.(p.Name);
s.DynPropInfo(i).GetMethod = p.GetMethod;
s.DynPropInfo(i).SetMethod = p.SetMethod;
end
end
end
methods(Static)
function obj = loadobj(s)
if isstruct(s)
newObj = myCls;
newObj.Prop1 = s.Prop1;
newObj.Prop2 = s.Prop2;
if isfield(s, 'DynPropInfo')
for i=1:numel(s.DynPropInfo)
p=addprop(newObj, s.DynPropInfo(i).Name);
p.SetMethod = s.DynPropInfo(i).SetMethod;
p.GetMethod = s.DynPropInfo(i).GetMethod;
newObj.(s.DynPropInfo(i).Name) = s.DynPropInfo(i).Value;
end
end
obj = newObj;
else
obj = s;
end
end
end
end