How to create a function handle to an object's method?

Hi, everyone.
I wanna create a function handle to an object's method. I have two classes, my_class1 and my_class2. my_class2 has a instance of my_class1 as its property. What I want to do is to create function handles to the instance of my_class1, and to use them in my_class2's method. Here's my code and when I tried to run it, it says "Unrecognized function obj.instance_of_my_class1.foo1". What is the correct way? I know eval() can do that, but it's evil isnt it?
classdef my_class1
methods
function foo1(obj, arg1, arg2)
% do something
end
function foon(obj, arg1, arg2)
% do something
end
function obj = my_class1(arg1, arg2)
% do something
end
end
end
classdef my_class2
properties
instance_of_my_class1
func_handles
end
methods
function obj = my_class2()
obj.instance_of_my_class1 = my_class1(1, 2)';
f_names = methods(obj.instance_of_my_class1); % names of my_class1's public methods
obj.func_handles = containers.Map(); % function name -> handle mapping
for f_name = f_names
handle = str2func(strcat('obj.instance_of_my_class1.', f_name{1, 1})); % HOW?
obj.func_handles(f_name) = handle;
end
end
function foo(obj, function_name)
% for example
f = obj.func_handles(function_name);
f(); % Unrecoginsed function
end
end
end

 採用された回答

Matt J
Matt J 2021 年 12 月 24 日

1 投票

tmp=obj.instance_of_my_class1;
for f_name = f_names
obj.func_handles(f_name) = @(varargin)tmp.(f_name)(varargin{:});
end

4 件のコメント

D D
D D 2021 年 12 月 24 日
It works, thank you! And I find that using str2func(f_name) and simply call it like f_name(obj.instance_of_my_class1, arg1, arg2 ...) also works.
D D
D D 2022 年 1 月 1 日
What if my_class1 is a handle class?
Matt J
Matt J 2022 年 1 月 1 日
Should that matter?
D D
D D 2022 年 1 月 2 日
Doesn't matter. Made a mistake.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeHandle Classes についてさらに検索

質問済み:

D D
2021 年 12 月 24 日

コメント済み:

D D
2022 年 1 月 2 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by