Static class call via string variable
이전 댓글 표시
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
Daniel Shub
2013년 4월 28일
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?
채택된 답변
추가 답변 (2개)
per isakson
2013년 4월 27일
편집: per isakson
2013년 4월 27일
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
Jim Hokanson
2017년 10월 17일
Cedric
2017년 10월 17일
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
2017년 10월 17일
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) ;
카테고리
도움말 센터 및 File Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!