【发布时间】:2015-07-07 13:01:50
【问题描述】:
我有一大组由接口类链接在一起的小型相关类。所有类都实现一个静态方法,该方法检索和处理特定于该类的数据。
该静态方法的输出需要至少以两种方式格式化。由于从一种格式到另一种格式的转换总是相同且相当琐碎(虽然很长),我想我会在超类中将它实现为一个具体的、密封的、静态方法。
但是,我遇到了以下问题:
% (in Superclass.m)
classdef SuperClass < handle
methods (Static, Abstract)
[arg1, arg2] = subsStaticMethod;
end
methods (Sealed, Static)
function [other_arg1, other_arg2] = supersStaticMethod
% Get data here
[arg1, arg2] = (???).subsStaticMethod
% transform data here
% ...
end
end
end
% (in Subclass.m)
classdef SubClass < SuperClass
methods (Static)
function [arg1, arg2] = subsStaticMethod
% Get class-specific data here
% ...
end
end
end
据我所知,这种设计无法调用SubClass.supersStaticMethod(),因为静态方法需要使用类名显式调用。也就是说,没有办法在上面的SuperClass.supersStaticMethod中插入子类名代替(???)。
我尝试过的事情:
-
mfilename('class')这不起作用,因为它总是返回'SuperClass' -
dbstack不包含该方法实际上是从子类调用的信息
我知道我可以通过将supersStaticMethod 设为非静态并在临时实例(如SubClass().supersStaticMethod())上调用该方法来解决此问题。或者在每个子类中创建一个小的包装器方法,该方法只使用mfilename('class') 作为参数调用超类方法。或者其他 100 种看起来同样笨拙的东西中的任何一种。
但我真的很想知道是否有一些meta.class 诡计或可以干净地解决这个问题的东西。我找到的只是this dated thread,它以编程方式处理 MATLAB 命令行以获取子类名称。
但是,我的类将在脚本/函数中使用,命令行使用将仅用于调试目的...
有什么想法吗?
【问题讨论】:
标签: matlab oop inheritance static-methods