2017-08-06 125 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