Humam Helfawi
Humam Helfawi

Reputation: 20264

Get Class property by its name

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

Answers (1)

Cris Luengo
Cris Luengo

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':

  1. using eval (not recommended!):

    eval(['obj.',str])
    
  2. using subsref (or subsasgn for assignment):

    S = substruct('.',str);
    subsref(obj,S)
    
  3. using getfield:

    getfield(obj,str)
    
  4. 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

Related Questions