フィルターのクリア

Can I find out if a class is an abstract class before trying to instantiate it?

5 ビュー (過去 30 日間)
Sam
Sam 2012 年 7 月 17 日
回答済み: Kyle 2023 年 11 月 3 日
Can i somehow say:
if isAbstract(className)
% do something
else
% do something else
end

採用された回答

per isakson
per isakson 2012 年 7 月 17 日
編集済み: per isakson 2012 年 7 月 17 日
A class is abstract if any of its properties or methods is abstract.
It's possible to write a function, is_abstract. Start:
mco = ?my_class
mco.PropertyList
mco.MethodList
any([mco.MethodList.Abstract])
.
or better
mcls = meta.class.fromName('ClassName')
  3 件のコメント
per isakson
per isakson 2012 年 7 月 17 日
Wouldn't calling an abstract method in a class definition be an error?
Daniel Shub
Daniel Shub 2012 年 7 月 18 日
@Walter, but that "hidden" abstract method would be abstract and eventually caught. The metaclass object has access to all methods and properties (even private ones), so I do not think it needs to be recursive.

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

その他の回答 (4 件)

Image Analyst
Image Analyst 2012 年 7 月 17 日
I don't think so. But you should know just by looking at the code, or just try it and see. Why would you ever not know what you're calling and have to use the test you you described? Worst case, you could wrap your method call in a try/catch to do what you want, but I would recommend knowing beforehand than doing that.

Sam
Sam 2012 年 7 月 18 日
thank you per, that did the trick.
the reason for the question was i am writing a test function that loops through all classes in a directory and instantiates them, but abstract classes were a problem.

Daniel Shub
Daniel Shub 2012 年 7 月 18 日
It might be quicker to try and create the object in a try-catch and deal with errors when they happen.

Kyle
Kyle 2023 年 11 月 3 日
You can create a simple function to do this:
function tf = isClassAbstract(className)
tf = meta.class.fromName(className).Abstract;
end
The Abstract property of meta.class is true "if the class or any property or method has its Abstract attribute set to true."

カテゴリ

Help Center および File ExchangeClass Introspection and Metadata についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by