2017-08-06 127 views

回答

2

metaclass返回meta.class对象,其中包含有关被查询的类信息。此meta.class对象的实用属性是PropertyList,其中包含有关该类的所有属性(包括DefiningClass)的信息。

使用下面的类定义为例:

classdef asuperclass 
    properties 
     thesuperproperty 
    end 
end 

classdef aclass < asuperclass 
    properties 
     theclassproperty 
    end 
end 

现在,我们可以查询的aclass的属性,以确定他们来自何处:

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) 

其中返回:

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

你可以把它包装成一个简单的帮助函数。例如:

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