get list of subclasses

14 views (last 30 days)
Jonas Reber
Jonas Reber on 12 Apr 2011
Commented: Robin on 10 Jul 2023
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!

Accepted Answer

Jonas Reber
Jonas Reber on 12 Apr 2011
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 Comment
Robin
Robin on 10 Jul 2023
Nice solution!
Be aware though that this will not work if classes are defined in a package folder (starting with +).

Sign in to comment.

More Answers (1)

Yannick T
Yannick T on 20 Apr 2011
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 Comments
Yannick T
Yannick T on 20 Apr 2011
Well, yes. But not in the conditional, which was the essential part for me :)
Jonas Reber
Jonas Reber on 3 May 2011
I like that, thanks!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!