Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test method existence on Objects

Tags:

oop

matlab

I have a cell array of Matlab objects, something like:

objs = {Object1(), Object2(), Object3()};

These objects are all of different types. Some of them will have a method, let's call it myMethod(). I want to do something like:

for o = objs
  if hasMethod(o, 'myMethod()')
    o.myMethod();
  end
end

and my difficulty is that I don't know how to do hasMethod - exist doesn't seem helpful here.

I could use a try - catch, but I'd rather do something neater. Is there a way to do this? Should I just change my design instead?

like image 424
Richante Avatar asked Feb 20 '26 00:02

Richante


2 Answers

Another option is to use the meta class.

  obmeta = metaclass(ob);
  methodNames = cellfun(@(x){x.Name},obmeta.Methods);

You can also get additional information from obmeta.Methods like

  • Amount of input/output parameters.
  • Access type
  • In which class the method is defined.

Also, metaclass can be constructed from the name of the class, without an instance, which can be an advantage in some situations.

like image 122
Andrey Rubshtein Avatar answered Feb 21 '26 15:02

Andrey Rubshtein


Ah, found it. Not very exciting - you can get a list of methods with the methods command. So to check if an object has a method,

if any(strcmp(methods(o), 'myMethod'))
  o.myMethod();
end
like image 38
Richante Avatar answered Feb 21 '26 15:02

Richante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!