Cannot retrieve argument list from a class constructor with arguments checking
2 views (last 30 days)
Show older comments
Daniele Lupo
on 22 Sep 2024
Commented: Daniele Lupo
on 23 Sep 2024
I've the following class:
classdef Main
%MAIN Summary of this class goes here
% Detailed explanation goes here
properties (Access = private)
logger;
options;
end
methods (Access = public)
function this = Main(options, logger)
%MAIN Construct an instance of this class
% Detailed explanation goes here
this.logger = logger;
this.options = options;
end
end
end
I want to retrieve the list of arguments of the constructor, and I do this way:
c = ?Main;
c.MethodList.InputNames
I obtain
ans =
2×1 cell array
{'options'}
{'logger' }
And everything is ok.
Now I also want to add a check on the arguments, to be sure that they are of the correct type. So I've updated my class this way:
classdef Main% < App.Interfaces.Component
%MAIN Summary of this class goes here
% Detailed explanation goes here
properties (Access = private)
logger;
options;
end
methods (Access = public)
function this = Main(options, logger)
%MAIN Construct an instance of this class
% Detailed explanation goes here
arguments
options (1, 1) App.Options
logger (1, 1) App.Logger
end
this.logger = logger;
this.options = options;
end
end
end
But now, If I try to re-run the code for retrieving the arguments, I obtain
ans =
1×1 cell array
{'varargin'}
Adding the check does not allow me to retrieve the arguments anymore, because I obtain only varargin.
Why this happens? Is there a way to add the arguments check and retrieve correctly the names of the constructor arguments anyway?
0 Comments
Accepted Answer
Venkat Siddarth Reddy
on 22 Sep 2024
Hi Daniele,
When you add the "arguments" block to your constructor, MATLAB treats the input arguments as a single "varargin" cell array for validation purposes. This is why you see "{'varargin'}" instead of the individual argument names.
Unfortunately, I don't see a way from the properties of "Main" class meta class to determine the constructor argument names. The following are the properties of the "Main" class meta class.
className = "Main";
mc = matlab.metadata.Class.fromName(className)
ctor = mc.MethodList(strcmp({mc.MethodList.Name}, className))
In this scenario, I would recommend creating a custom method in the class, which has explictly stated information about the argument types:
methods (Access = public, Static)
function argsInfo = getConstructorArgs()
argsInfo = struct('options', 'App.Options', 'logger', 'App.Logger');
end
end
I hope it helps!
Regards
Venkat Siddarth V
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!