How can I force Matlab to run an enum class constructor?

11 views (last 30 days)
I have the following enum class:
classdef MyEnum
properties
prop1
end
enumeration
A( 1, 2 )
B( 3, 4 )
end
methods( Access = public )
function this = MyEnum( x, y )
fprintf( 'Running MyEnum constructor...\n' );
this.prop1 = x + y;
end
end
end
The first time I instantiate an object of type MyEnum after opening Matlab or clearing classes, or when I make a change to MyEnum.m and save it, Matlab runs the constructor once for each enumeration:
>> foo = MyEnum.A;
Running MyEnum constructor...
Running MyEnum constructor...
>> foo = MyEnum.B;
>> clear classes
>> foo = MyEnum.B;
Running MyEnum constructor...
Running MyEnum constructor...
>>
These seem to be the only ways to run the constructor; running "clear MyEnum" and instantiating another object also doesn't run the constructor. I'd like to run it without clearing everything (as "clear classes" does). Is there a way to do this?

Answers (1)

Matt J
Matt J on 28 Feb 2020
I'd like to run it without clearing everything (as "clear classes" does). Is there a way to do this?
You don't need to clear everything. Clearing both the class and any lingering objects of the class in the workspace would be sufficient. For example,
>> clear classes;
>> obj=myclass.A;
Running myclass constructor...
Running myclass constructor...
>> clear obj; clear myclass;
>> obj=myclass.A;
Running myclass constructor...
Running myclass constructor...
  1 Comment
Matt
Matt on 28 Feb 2020
Excellent! But, and I probably should've mentioned this before but I was hoping a simple explanation would help and I wouldn't need to dive into really hairy details, my issue is when running unit testing code on the class - it's a property of the test case so I can run unit testing on it with ParameterCombination = 'sequential':
classdef MyEnumTest < matlab.unittest.TestCase
properties( TestParameter )
testEnum = arrayfun( @( x ) x, ...
eval( 'enumeration( ''myPackage.MyEnum'' )' ), ...
'UniformOutput', false );
end
methods( Test = true, ParameterCombination = 'sequential' )
function SomeUnitTest( testCase, testEnum )
% Test each enumeration
end
end
end
I'm running the unit testing with the code coverage plugin and the MyEnum constructor isn't getting picked up. I was hoping to add a second simple test and just run the constructor. I could set testEnum to a cell array of strings, but then I'd have to update it if/when the enumeration list changes.

Sign in to comment.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!