Reputation: 20264
Is it possible to reach a Class Property by its name dynamically?
classdef ClassA < handle
properties
a
end
end
obj = ClassA;
obj.GetVar('a') = 10;
Is there something like GetVar('a')
?
Upvotes: 0
Views: 125
Reputation: 60444
There are 4 ways to access a field of a struct or a custom object obj
when its name is given by a string str
(that I know of). The following are all equivalent to obj.a
, given str='a'
:
using eval
(not recommended!):
eval(['obj.',str])
using subsref
(or subsasgn
for assignment):
S = substruct('.',str);
subsref(obj,S)
using getfield
:
getfield(obj,str)
using the functional form of the dot operator:
obj.(str)
The latter is of course to be preferred.
subsref
and subsasgn
are interesting because they are the methods you would overload in your class to modify the behavior of indexing. The getfield
method has very limited uses, but once was the only sane way of accessing fields using dynamic names, before the obj.(str)
syntax was introduced.
Upvotes: 4