Static class call via string variable
Afficher commentaires plus anciens
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 commentaire
Daniel Shub
le 28 Avr 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?
Réponse acceptée
Plus de réponses (2)
per isakson
le 27 Avr 2013
Modifié(e) : per isakson
le 27 Avr 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 commentaires
Jim Hokanson
le 17 Oct 2017
Cedric
le 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
le 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 commentaire
Jim Hokanson
le 27 Avr 2013
Catégories
En savoir plus sur Construct and Work with Object Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!