Leila
Leila

Reputation: 206

Finding inheritance property of a matlab class method

How can I find out whether a property is inherited from a super class or is defined in the class definition directly? Assuming obj is an instance of the class, I have tried:

properties(obj)
metaclass(obj)

Upvotes: 1

Views: 93

Answers (1)

sco1
sco1

Reputation: 12214

metaclass returns a meta.class object that contains information about the class that is queried. The useful property of this meta.class object is the PropertyList, which contains information about all the properties of the class, including the DefiningClass.

Using the following class definitions as an example:

classdef asuperclass
    properties
        thesuperproperty
    end
end

and

classdef aclass < asuperclass
    properties
        theclassproperty
    end
end

We can now query the properties of aclass to determine where they came from:

tmp = ?aclass;
fprintf('Class Properties: %s, %s\n', tmp.PropertyList.Name)
fprintf('''theclassproperty'' defined by: %s\n', tmp.PropertyList(1).DefiningClass.Name)
fprintf('''thesuperproperty'' defined by: %s\n', tmp.PropertyList(2).DefiningClass.Name)

Which returns:

Class Properties: theclassproperty, thesuperproperty
'theclassproperty' defined by: aclass
'thesuperproperty' defined by: asuperclass

You can wrap this into a simple helper function. For example:

function classStr = definedby(obj, queryproperty)
tmp = metaclass(obj);
idx = find(ismember({tmp.PropertyList.Name}, queryproperty), 1);  % Only find first match

% Simple error check
if idx
    classStr = tmp.PropertyList(idx).DefiningClass.Name;
else
    error('Property ''%s'' is not a valid property of %s', queryproperty, tmp.Name)
end
end

Upvotes: 2

Related Questions