如何在超类的静态函数中获取调用子类的名称?

How to get the calling subclass' name in a superclass' static function?

假设我们有 Check.m:

classdef Check < handle
methods (Static)
    function doStuff()
        if isCalledFromAssertSubclass
            % do this stuff only if called as Assert.doStuff(), not if called as Check.doStuff()
        end
        % do other stuff
    end
end
end

和Assert.m:

classdef Assert < Check
    % nop
end

如评论中所写,我希望 Check.doStuff() 仅执行 "do other stuff" 行,并且 Assert.doStuff() 也执行 if isCalledFromAssertSubclass 块。

我想使用静态方法,这样我就不需要在需要断言时创建断言对象。使用全局断言对象也非常丑陋,并且在我想使用断言的每个函数中都需要一个 global assert 行。支票也是如此。

所以有两个问题:

  1. 因为这些是静态的 classes,所以没有机会使用 class(obj) 或任何其他非静态的 class 属性 或函数。
  2. dbstack 不支持继承,并且总是 returns Check 调用 class,也用于 Assert.doStuff.

我确实找到了一个可行的解决方案,它使用 dbstackdbtype 的组合来读取调用来自的行,即显示 Assert.doStuff() 的行。然而,它涉及两个调试功能,可能不应该在生产代码中使用,更重要的是,dbtype 非常慢(在我的情况下,70 秒中的 30 秒!)。

我可以改用一个包(目录 +Check 中有函数文件)并创建一个符号链接 +Assert -> +Check。然后我可以检查文件名,但那是 a) 不可移植,b) 非常难看,c) 也有点慢(我想)。

有没有更快的方法?

为什么不重载 Assert 的静态方法,并让它在完成后调用父方法?这是使用继承的正常方式:您不希望父 Check 了解其子 Assert.

的任何信息

这是它的样子:

classdef Assert < Check
methods (Static)
    function doStuff()
        % do some stuff
        Check.doStuff()
    end
end
end

, the above works as long as Check.doStuff is not sealed. A sealed method cannot be overloaded. See the documentation.