动态类生成
如何从其内容动态创建类?
事实上,我已经创建了一种 Matlab 引擎类实例化和执行,其中我可以列出目录中的所有类文件 (*.m),实例化它们(使用“eval(clasnname)”)并使用这些对象。
现在我想“即时”更改这些文件的文件内容,然后实例化它们并使用这些新对象。
所以我编写了一个函数来将文件的内容读取到字符串中,替换/添加一些内容到这个字符串中,并且......我不知道如何从这个字符串创建一个对象(类的实例)(包含“classdef myClass < myMotherClass \n ... end”)。 (我知道我可以使用此字符串内容在文件系统上创建一个新文件,然后像我已经完成的那样使用 eval(...) ,但我尝试在不创建新的物理文件的情况下执行此操作)。
有人知道该怎么做吗?
How to dynamically create a class from its content?
In fact I've create a kind of Matlab engine classes instantiation and execution, in which I can list all class files (*.m) in a directory, instantiate them (with 'eval(clasnname)') and use theses objects.
Now I want to change the file content of theses files "on the fly", and then, instantiate them and use these new objects.
So I've written a function to read the content of file into a string, replace/add some contents into this string and... I don't know how to create an object (instance of a class) from this string (which contains 'classdef myClass < myMotherClass \n ... end'). (I know that I can create a new file on my filesystem with this string content and then use eval(...) as I've already done, but I try to do this without create new physical file).
Does someone know how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这在 MATLAB 中是不可能的,与 Ruby 这样的纯面向对象编程语言不同。如果是的话,那么就会有某种方法来构建
meta.class
对象,但没有。我认为编写
classdef
文件是您唯一的选择。您可能需要以编程方式调用rehash
才能让它加载新定义,如果存在使用旧定义的现有对象,那么它根本不会加载新定义,直到您清除所有内容。我想真正的问题是“为什么你需要这样做?”
旁白:使用
feval
而不是eval
来创建新类的实例。I don't think that this is possible in MATLAB, unlike in a pure object-oriented programming language like Ruby. If it were, then there would be some way of building a
meta.class
object, but there's not.I think that writing a
classdef
file is your only option. You may need to programmatically callrehash
in order to get it to load the new definition and if there are existing objects using the old definition, then it won't load the new definition at all until you clear everything.I suppose the real question is "Why do you need to do this?"
Aside: Use
feval
rather thaneval
to create instances of your new class.MATLAB 允许您通过添加动态属性在运行时修改对象实例,但你不能添加方法。
MATLAB does allow you to modify object instances at runtime by adding dynamic properties, but you cannot add methods.
是的,当然你可以在 matlab 中创建一个动态类,通过子类化为dynamicprops,你甚至可以从一个字符串创建一个完整的类,比如文件或 JSON 或其他什么。请参阅 myDynamicClass 上的示例 FEX
Yes of course you can create a dynamic class in matlab, by subclassing to dynamicprops, and you can even create an entire class from a string, like a file or JSON or whatever. See my example myDynamicClass on FEX