How can I make such that every method call to a class is routed through a wrapper
Show older comments
Is there a way to automatically wrap every method call to a class in a wrapper function in MATLAB? For example, suppose I have a class with methods method1 and method2 and a wrapper function wrapper_func. The wrapper_func should:
- Print the inputs and the name of the method.
- Call the actual method (e.g., method1).
- Print the outputs of the method.
When I create an object obj of this class and call obj.method1, it should implicitly call wrapper_func with method1 so that the wrapper function handles the input/output printing and method execution. How can this be achieved in MATLAB?
Accepted Answer
More Answers (1)
SACHIN KHANDELWAL
on 28 Jun 2024
You can achieve this in MATLAB by using a combination of class inheritance and method overloading. You'll need to create a base class that defines a generic method call handler, and then use this base class in your actual class to wrap me
Let's say we have created a superclass with two methods: "method1" and "method2".
classdef mySuperClass
methods
function output = method1(obj, input)
output = input * 2;
end
function output = method2(obj, input)
output = input + 10;
end
end
end
We have now created another class that inherits from the superclass. This means that the new class has access to the properties and methods of the superclass.
classdef myBaseClass < mySuperClass
methods
function wrapper_fcn(obj)
% apply your logic to handle method name etc.
output1 = obj.method1(3)
output2 = obj.method2(4)
end
end
end
I hope this is helpful.
Thanks!
1 Comment
Alexander
on 28 Jun 2024
Categories
Find more on MATLAB Compiler in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!