Static class call via string variable
Show older comments
Is it possible to call a static method or Constant property from a class whose name is represented by a string without using eval?
my_class_string = 'my_class'
eval([my_class_string '.MY_CONSTANT_PROPERTY'])
1 Comment
Daniel Shub
on 28 Apr 2013
At the point in which it is a string it might, and probably is, too late. How do you end up with a string and not an object?
Accepted Answer
More Answers (2)
per isakson
on 27 Apr 2013
Edited: per isakson
on 27 Apr 2013
It's without eval
foo = str2func( my_class_string );
obj = foo();
obj.MY_CONSTANT_PROPERTY
ans =
17
where
classdef my_class
properties ( Constant = true )
MY_CONSTANT_PROPERTY = 17
end
end
An alternative
obj = feval( 'my_class' )
obj.MY_CONSTANT_PROPERTY
But, is it any better than eval? And it does neither depend on static nor constant.
4 Comments
Jim Hokanson
on 17 Oct 2017
Cedric
on 17 Oct 2017
Could you e.g. test if nargin==0 in the constructor and do nothing, if you meant "not ideal" because creating the object may be resource consuming?
Jim Hokanson
on 17 Oct 2017
I sympathize! ;)
I am increasingly implementing more complex constructors that manage special cases though, e.g.
methods
function obj = Xyz( x, y, varargin )
% x must be a num array, yet ..
if ischar( x ) && strcmpi( x, 'test' )
do something
return
end
assert( isnumeric(x), '...' ) ;
assert( isnumeric(y), '...' ) ;
if ~isempty( varargin )
parser = inputParser ;
% .. more lengthy parsing, but no parser if not necessary
end
...
Yes, you can proceed the same way as with dynamic field names:
myObject = myClass() ;
methodName = 'foo' ;
x = myObject.(methodName)(arg1, arg2) ;
1 Comment
Jim Hokanson
on 27 Apr 2013
Categories
Find more on Construct and Work with Object Arrays 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!