MATLAB Answers

How can I check if a string is the name of a custom subclass?

2 views (last 30 days)
I have a cell array of strings with names of files that match certain criteria. Now want to test if each of these strings is 1) the name of a class and 2) if it is a class, is it a subclass of the MATLAB Unit Test class. How can I do this?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 29 Apr 2020

You can use a combination of the "exist", "ismember", and "superclasses" functions. This lets you see if a given string represents a class name and whether that class is a subclass of the MATLAB Unit Test superclass. The general syntax is as follows:

exist("classname", 'class') && ismember("superclassName", superclasses("classname"))

In this both "classname" and "superclassName" are strings. This will return logical 1 if "classname" is both a class and "superclassName" appears in the set of its superclasses. This can handle many levels of inheritance, since the "superclasses" function does not only include direct superclasses.


Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 18 May 2020
Another way to do this is to use the meta class functionality. If you construct a metaclass object from a name and that name is not the name of a class, the returned object is empty.
B = meta.class.fromName('bench') % bench.m is not a class file
isAClass = ~isempty(B) % false
The relational operators <, <=, >, >=, ==, and ~= are overloaded for meta.class objects. As stated on the documentation page for these objects < means "Less than function (ClsA < ClsB). Use to determine if ClsA is a strict subclass of ClsB (i.e., a strict subclass means ClsX < ClsX is false)."
As an example, RandStream is a class in MATLAB but it is not a test class.
R = meta.class.fromName('RandStream');
isAClass = ~isempty(R) % true
TC = ?matlab.unittest.TestCase; % Another way of creating a meta.class object
R < TC % False, RandStream is not a subclass of matlab.unittest.TestCase
TC < R % Also false, matlab.unittest.TestCase is not a subclass of RandStream


Sign in to comment.




Community Treasure Hunt

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

Start Hunting!