简介:
在解决方案的过程中,我似乎找到了 meta.class 类的一个未记录的静态方法,它返回所有缓存的类(当有人调用 clear classes 时几乎所有被删除的东西)以及(完全是偶然的)制作了一个工具来检查classdef 文件是否有错误。
由于我们想要找到 所有 子类,因此确定的方法是列出 所有已知 em> 类,然后检查每个类是否派生自任何其他类。为了实现这一点,我们将我们的工作分为两类:
该脚本有两个输入标志(includeBulkFiles,includePackages),用于确定每种类型的类是否应包含在输出列表中。
完整代码如下:
function [mc_list,subcls_list] = q37829489(includeBulkFiles,includePackages)
%% Input handling
if nargin < 2 || isempty(includePackages)
includePackages = false;
mp_list = meta.package.empty;
end
if nargin < 1 || isempty(includeBulkFiles)
includeBulkFiles = false;
mb_list = meta.class.empty; %#ok
% `mb_list` is always overwritten by the output of meta.class.getAllClasses;
end
%% Output checking
if nargout < 2
warning('Second output not assigned!');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Get classes list from bulk files "laying around" the MATLAB path:
if includeBulkFiles
% Obtain MATLAB path:
p = strsplit(path,pathsep).';
if ~ismember(pwd,p)
p = [pwd;p];
end
nPaths = numel(p);
s = what; s = repmat(s,nPaths+20,1); % Preallocation; +20 is to accomodate rare cases
s_pos = 1; % where "what" returns a 2x1 struct.
for ind1 = 1:nPaths
tmp = what(p{ind1});
s(s_pos:s_pos+numel(tmp)-1) = tmp;
s_pos = s_pos + numel(tmp);
end
s(s_pos:end) = []; % truncation of placeholder entries.
clear p nPaths s_pos tmp
%% Generate a list of classes:
% from .m files:
m_files = vertcat(s.m);
% from .p files:
p_files = vertcat(s.p);
% get a list of potential class names:
[~,name,~] = cellfun(@fileparts,[m_files;p_files],'uni',false);
% get listed classes:
listed_classes = s.classes;
% combine all potential class lists into one:
cls_list = vertcat(name,listed_classes);
% test which ones are actually classes:
isClass = cellfun(@(x)exist(x,'class')==8,cls_list); %"exist" method; takes long
%[u,ia,ic] = unique(ext(isClass(1:numel(ext)))); %DEBUG:
% for valid classes, get metaclasses from name; if a classdef contains errors,
% will cause cellfun to print the reason using ErrorHandler.
[~] = cellfun(@meta.class.fromName,cls_list(isClass),'uni',false,'ErrorHandler',...
@(ex,in)meta.class.empty(0*fprintf(1,'The classdef for "%s" contains an error: %s\n'...
, in, ex.message)));
% The result of the last computation used to be assigned into mc_list, but this
% is no longer required as the same information (and more) is returned later
% by calling "mb_list = meta.class.getAllClasses" since these classes are now cached.
clear cls_list isClass ind1 listed_classes m_files p_files name s
end
%% Get class list from classes belonging to packages (takes long!):
if includePackages
% Get a list of all package classes:
mp_list = meta.package.getAllPackages; mp_list = vertcat(mp_list{:});
% see http://www.mathworks.com/help/matlab/ref/meta.package.getallpackages.html
% Recursively flatten package list:
mp_list = flatten_package_list(mp_list);
% Extract classes out of packages:
mp_list = vertcat(mp_list.ClassList);
end
%% Combine lists:
% Get a list of all classes that are in memory:
mb_list = meta.class.getAllClasses;
mc_list = union(vertcat(mb_list{:}), mp_list);
%% Map relations:
try
[subcls_list,discovered_classes] = find_superclass_relations(mc_list);
while ~isempty(discovered_classes)
mc_list = union(mc_list, discovered_classes);
[subcls_list,discovered_classes] = find_superclass_relations(mc_list);
end
catch ex % Turns out this helps....
disp(['Getting classes failed with error: ' ex.message ' Retrying...']);
[mc_list,subcls_list] = q37829489;
end
end
function [subcls_list,discovered_classes] = find_superclass_relations(known_metaclasses)
%% Build hierarchy:
sup_list = {known_metaclasses.SuperclassList}.';
% Count how many superclasses each class has:
n_supers = cellfun(@numel,sup_list);
% Preallocate a Subclasses container:
subcls_list = cell(numel(known_metaclasses),1); % should be meta.MetaData
% Iterate over all classes and
% discovered_classes = meta.class.empty(1,0); % right type, but causes segfault
discovered_classes = meta.class.empty;
for depth = max(n_supers):-1:1
% The function of this top-most loop was initially to build a hierarchy starting
% from the deepest leaves, but due to lack of ideas on "how to take it from here",
% it only serves to save some processing by skipping classes with "no parents".
tmp = known_metaclasses(n_supers == depth);
for ind1 = 1:numel(tmp)
% Fortunately, SuperclassList only shows *DIRECT* supeclasses. Se we
% only need to find the superclasses in the known classees list and add
% the current class to that list.
curr_cls = tmp(ind1);
% It's a shame bsxfun only works for numeric arrays, or else we would employ:
% bsxfun(@eq,mc_list,tmp(ind1).SuperclassList.');
for ind2 = 1:numel(curr_cls.SuperclassList)
pos = find(curr_cls.SuperclassList(ind2) == known_metaclasses,1);
% Did we find the superclass in the known classes list?
if isempty(pos)
discovered_classes(end+1,1) = curr_cls.SuperclassList(ind2); %#ok<AGROW>
% disp([curr_cls.SuperclassList(ind2).Name ' is not a previously known class.']);
continue
end
subcls_list{pos} = [subcls_list{pos} curr_cls];
end
end
end
end
% The full flattened list for MATLAB R2016a contains about 20k classes.
function flattened_list = flatten_package_list(top_level_list)
flattened_list = top_level_list;
for ind1 = 1:numel(top_level_list)
flattened_list = [flattened_list;flatten_package_list(top_level_list(ind1).PackageList)];
end
end
此函数的输出是 2 个向量,在 Java 术语中可以认为是Map<meta.class, List<meta.class>>:
-
mc_list - meta.class 类的对象向量,其中每个条目包含有关 MATLAB 已知的一个特定类的信息。这些是我们Map 的“钥匙”。
-
subcls_list - 一个(相当稀疏的)单元向量,包含出现在mc_list 对应位置的类的已知直接子类。这些是我们Map 的“值”,本质上是List<meta.class>。
一旦我们有了这两个列表,只需在mc_list 中找到您感兴趣的类的位置,并从subcls_list 获取其子类列表。如果需要间接子类,则对子类也重复相同的过程。
或者,可以使用例如表示层次结构。一个logicalsparse邻接矩阵A,其中ai,j==1表示类i是j的子类。那么这个矩阵的转置可以表示相反的关系,即aTi,j==1表示i是一个超级类j。牢记邻接矩阵的这些属性允许非常快速地搜索和遍历层次结构(避免需要对meta.class 对象进行“昂贵的”比较)。
几点说明:
- 由于未知原因(缓存?),代码可能由于错误(例如
Invalid or deleted object.)而失败,在这种情况下重新运行它会有所帮助。我添加了一个try/catch,它会自动执行此操作。
- 代码中有 2 个实例,其中数组在循环内增长。这当然是不需要的,应该避免。由于缺乏更好的想法,代码就这样留下了。
- 如果算法的“发现”部分无法避免(通过某种方式首先找到所有类),则可以(并且应该)对其进行优化,以便每次迭代只对以前未知的类进行操作。李>
- 运行此代码的一个有趣的意想不到的好处是它会扫描所有已知的
classdefs 并报告其中的任何错误 - 这可能是一个有用的工具,可以在而对于任何使用 MATLAB OOP 的人 :)
- 感谢@Suever 提供一些有用的建议。
与奥列格的方法比较:
为了将这些结果与 Oleg 的示例进行比较,我将使用在我的计算机上运行上述脚本的输出(包含约 20k 类;上传 here 作为 .mat 文件)。然后我们可以通过以下方式访问类映射:
hRoot = meta.class.fromName('sde');
subcls_list{mc_list==hRoot}
ans =
class with properties:
Name: 'sdeddo'
Description: ''
DetailedDescription: ''
Hidden: 0
Sealed: 0
Abstract: 0
Enumeration: 0
ConstructOnLoad: 0
HandleCompatible: 0
InferiorClasses: {0x1 cell}
ContainingPackage: [0x0 meta.package]
PropertyList: [9x1 meta.property]
MethodList: [18x1 meta.method]
EventList: [0x1 meta.event]
EnumerationMemberList: [0x1 meta.EnumeratedValue]
SuperclassList: [1x1 meta.class]
subcls_list{mc_list==subcls_list{mc_list==hRoot}} % simulate recursion
ans =
class with properties:
Name: 'sdeld'
Description: ''
DetailedDescription: ''
Hidden: 0
Sealed: 0
Abstract: 0
Enumeration: 0
ConstructOnLoad: 0
HandleCompatible: 0
InferiorClasses: {0x1 cell}
ContainingPackage: [0x0 meta.package]
PropertyList: [9x1 meta.property]
MethodList: [18x1 meta.method]
EventList: [0x1 meta.event]
EnumerationMemberList: [0x1 meta.EnumeratedValue]
SuperclassList: [1x1 meta.class]
在这里我们可以看到最后一个输出只有 1 个类 (sdeld),而我们期望其中有 3 个 (sdeld,sdemrd,heston) - 这意味着 某些类此列表中缺少1。
相比之下,如果我们检查一个共同的父类,例如handle,我们会看到完全不同的画面:
subcls_list{mc_list==meta.class.fromName('handle')}
ans =
1x4059 heterogeneous class (NETInterfaceCustomMetaClass, MetaClassWithPropertyType, MetaClass, ...) array with properties:
Name
Description
DetailedDescription
Hidden
Sealed
Abstract
Enumeration
ConstructOnLoad
HandleCompatible
InferiorClasses
ContainingPackage
PropertyList
MethodList
EventList
EnumerationMemberList
SuperclassList
总而言之:此方法尝试索引 MATLAB 路径上的所有已知类。构建类列表/索引需要几分钟,但这是一个 1 次过程,稍后在搜索列表时会得到回报。它似乎遗漏了一些类,但找到的关系并不局限于相同的包、路径等。因此,它天生就支持多重继承。
1 - 我目前不知道是什么原因造成的。