Class handler to call static methods

I am new to OOP in MATLAB and I am trying to figure out how to make object handler, which could be used to call classes static methods.
Lets say I have two clases car and bike. Both have in common static method MakeSound().
Now I would like in the script have something like
vehHand = @car;
and later in the script use somehting like
vehHand.MakeSound();
I looks like @car is not handle to the object but just handle to the constructor of the class. Is there a way to call static method of a class, knowing the name of class as a string (for example className = "car")? I am pretty sure that something like
feval([className '.' 'MakeSound'])
or
eval([className '.' 'MakeSound()'])
would work but is there some "nicer" way to do this?

1 件のコメント

Raphaël Candelier
Raphaël Candelier 2022 年 9 月 13 日
編集済み: Raphaël Candelier 2022 年 9 月 13 日
Same question here.
For completeness, the class handle can be used by feval after conversion to a string:
feval([func2str(vehHand) '.MakeSound'])
But this is not really satisfying and can become pretty awful when parameters have to be passed to the static method.

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

回答 (1 件)

Matt J
Matt J 2022 年 9 月 13 日
編集済み: Matt J 2022 年 9 月 13 日

0 投票

h=@(varargin) feval([vehHand '.MakeSound'],varargin{:});
h(arg1, arg2,...,argN)

カテゴリ

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

製品

リリース

R2020b

タグ

質問済み:

2021 年 8 月 27 日

編集済み:

2022 年 9 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by