matlaboopmetaclassdynamic-properties

Retrieve the list of dynamic properties added to class in MATLAB OOP


With MATLAB it is possible to add dynamic properties to a class instance like this:

% Define a class supporting for dynamic properties
classdef DynamicClass < dynamicprops
end

% Add a dynamic property named 'toto' to some instance
c = DynamicClass();
c.addprop('toto');

Anyhow I did not find a way to later obtain the list of dynamic properties through reflection, indeed:

m = metaclass(c);

returns an empty list for properties:

PropertyList: [0x1 meta.property]

Even listing properties in dynamicprops superclass returns an empty list:

m.SuperClassList(1).PropertyList ==> 0x1 property array

Is there a way to obtain (through reflection) the list of dynamic properties added to a class ?

NB: Some workaround would be to maintain manual list newprop(end+1) = c.addprop(...) but it's not very practical to pass to another base class (where til now I was working with reflection to obtain information about properties in the child class).


Solution

  • Dynamic properties are not properties of the class, they're properties only of the object - note that if DynamicClass inherits from dynamicprops, then different objects of class DynamicClass can have a different set of properties:

    >> a = DynamicClass;
    >> b = DynamicClass;
    >> a.addprop('hello');
    >> a
    a = 
      DynamicClass with properties:
    
        hello: []
    >> b
    b = 
      DynamicClass with no properties.
    

    For this reason, you're not going to be able to get any information about them via reflection, which is by definition getting information about the class.

    You've given a solution (use properties to retrieve a list the names of all properties of the object, dynamic or not, then use findprop to get the property itself, and then get information about the property).

    This is likely to work OK in most cases, but note that properties only returns a list of the properties that are both Hidden = false and GetAccess = public (and that's true even if you call properties inside a method of the object). By default, properties added via addprop meet both of those criteria, but it's possible to change their attributes after adding them, and they won't show up with your solution. The same goes if you call fieldnames on the object.

    Another thing that might work for you would be to use isprop to directly check whether the object has a property of interest. This works even if the property is Hidden, or GetAccess = private. Usefully, isprop works on arrays of objects, so you can create an array of objects of class DynamicClass, then apply isprop to get an array of logicals.

    But the only way I know of reliably getting everything (private or not, hidden or not, and whether you know the names of the properties beforehand or not) is to just dump the object into a struct temporarily, then get the fieldnames, as @Marek suggests.