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?
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.classobject, but there’s not.I think that writing a
classdeffile is your only option. You may need to programmatically callrehashin 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
fevalrather thanevalto create instances of your new class.