get list of subclasses

17 次查看(过去 30 天)
Jonas Reber
Jonas Reber 2011-4-12
评论: Robin 2023-7-10
Hello Matlabers
I have a class "Filter" and some subclasses "xxFilter, "yyFilter", etc. They have a const property called "Name". I would now like to implement a funcation that gives me a list (Name) of all available classes that are subclasses of "Filter".
what I have so far:
flist = getAllFiles('myFilterFolder');
for i=1:numel(flist)
[~,filename,fileext,~]=fileparts(flist{i}); % get those names
if (exist(filename,'class') == 8) && (strcmp(fileext,'.m'))
% -----------------------------------------------------------
% here I would like to check if the class with name filename a class
% of type "Filter", if it would be an object, I would use
% isa(filename,'Filter'). But how do I achieve this with a string?
% -----------------------------------------------------------
% then I could add the name (class with name filename).Name to my
% string list
else
flist{i}=[]; % empty the cell
end
end
% cleanup empty cells
flist(cellfun(@isempty,flist)) = [];
As pointed out above I would like to check If there exists a class with name "filename" that is of type "Filter" just as I would do with "isa(.., 'Filter')".
I therefore need a function that allows me to access the class properties of tha class with a name given as a string (here filename)
Thank you so much!

采纳的回答

Jonas Reber
Jonas Reber 2011-4-12
I figured out how to resolve that problem when I realized the power of "eval()".
For anyone interested in doing something similar, here's the code I have now:
% list of all folders in FilterFunctions:
flist = getAllFiles('FilterFunctions');
% prepare result
filterlist = struct('Name',{},'Classname',{});
for i=1:numel(flist)
[~,filename,fileext]=fileparts(flist{i}); % get just the filename
if (exist(filename,'class') == 8) && (strcmp(fileext,'.m'))
try
if(isa(eval(filename),'Filter'))
filterlist(end+1) = struct( ...
'Name', eval([filename '.Name']), ...
'Classname',filename ...
);
end
catch % no problem - its eval
end
end
end
  1 个评论
Robin
Robin 2023-7-10
Nice solution!
Be aware though that this will not work if classes are defined in a package folder (starting with +).

请先登录,再进行评论。

更多回答(1 个)

Yannick T
Yannick T 2011-4-20
Hello Jonas,
I was trying to do something similar and your solution works fine. You could also do it in a slightly different way which doesn't require the use of eval():
if exist(filename, 'class') && ismember('Filter', superclasses(filename))
filterlist(end+1) = struct( ...
'Name', eval([filename '.Name']), ...
'Classname',filename ...
);
end
Yannick
  3 个评论
Yannick T
Yannick T 2011-4-20
Well, yes. But not in the conditional, which was the essential part for me :)
Jonas Reber
Jonas Reber 2011-5-3
I like that, thanks!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Assembly 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by