Handle undefined methods in Matlab by passing method's name and inputs to a function/method

Viewed 44

Assume we have a Matlab class called MyClas, as below,

classdef MyClass
   properties
      Value
   end
   methods
      function foo(input1, input2)
          ...
      end
   end
end

What I am looking for is having MyClass.anyThing(inputValue), where anyThing and inputValue are arbitrary strings and anyThing is not a defined method in MyClass, passes anyThing and inputValue as two strings to my foo function.

In other words, I want to be able to handle undefined methods by passing their name and inputs to a function/method as strings.

I am having a hard time to elaborate on my issue since I don't know if there is any technical term for what I am trying to pull off here. Yet, I managed to find this link from math works, which just customizes indexing operations and does not exactly address my issue.

1 Answers

You can emulate this by hacking in an implementation of subsref. Like this:

classdef MethodRedirector
    methods
        function varargout = subsref(obj, S)
            if numel(S) == 2 && strcmp(S(1).type, '.') && ...
                    strcmp(S(2).type, '()')
                % Looks like obj.method(args)
                fprintf('In method invocation to: %s with args:\n', S(1).subs);
                celldisp(S(2).subs);
            else
                [varargout{1:nargout}] = builtin('subsref', obj, S);
            end
        end
    end
end

The restriction is that callers must use the obj.method(args...) syntax, and cannot use the (usually equivalent) method(obj, args...) syntax.

Here's how that looks in practice:

>> mr = MethodRedirector; mr.someMethod(1, '2', magic(3))
In method invocation to: someMethod with args:
ans{1} =
     1
ans{2} =
2
ans{3} =
     8     1     6
     3     5     7
     4     9     2
Related