Cannot retrieve argument list from a class constructor with arguments checking
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Venkat Siddarth Reddy
2024-9-22
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!