【发布时间】:2012-05-29 23:28:55
【问题描述】:
我有一个继承自多个超类的类,我想获取该类具有的方法。天真地使用 methods() 从我正在使用的类中返回方法以及超类方法,但我对超类方法不感兴趣。
知道怎么做吗?我在 MATLAB 文档中找不到任何内容。
谢谢!
【问题讨论】:
-
您使用的是新式 MCOS 类(带有 classdef 文件)还是旧式类?
我有一个继承自多个超类的类,我想获取该类具有的方法。天真地使用 methods() 从我正在使用的类中返回方法以及超类方法,但我对超类方法不感兴趣。
知道怎么做吗?我在 MATLAB 文档中找不到任何内容。
谢谢!
【问题讨论】:
如果您的子类没有重新实现超类的任何方法(或者如果您可以忽略重新实现的方法),您可以使用函数 METHODS 和 SUPERCLASSES 来查找子类方法的列表也不是任何超类的方法。例如:
>> obj = 'hgsetget'; %# A sample class name
>> supClasses = superclasses(obj)
supClasses =
'handle' %# Just one superclass, but what follows should handle more
>> supMethods = cellfun(@methods,supClasses,... %# Find methods of superclasses
'UniformOutput',false);
>> supMethods = unique(vertcat(supMethods{:})); %# Get a unique list of
%# superclass methods
>> subMethods = setdiff(methods(obj),supMethods) %# Find methods unique to the
%# subclass
subMethods =
'get'
'getdisp'
'set'
'setdisp'
【讨论】:
即使这个问题已经解决,让我使用meta.class 功能添加另一个答案:
%# some class name
clname = 'hgsetget';
%# obtain class meta-info
mt = meta.class.fromName(clname);
%# get name of class defining each method
cdef = arrayfun(@(c)c.Name, [mt.MethodList.DefiningClass], 'Uniform',false);
%# keep only methods that are defined in the subclass
subMethods = {mt.MethodList(ismember(cdef,clname)).Name}
这个例子的结果:
subMethods =
'set' 'get' 'setdisp' 'getdisp' 'empty'
注意结果如何还包括所有非抽象类都具有的静态方法empty(用于创建该类的空数组)。
【讨论】: