How to recast a superclass object into a subclass based on internal information?

11 visualizaciones (últimos 30 días)
I recently put up this post asking some related questions about super- and sub-class uses. This asks a related question: how can I take an object of a superclass, read some data from it, and assign it to a sub-class based on that information.
Here is a rather specific example. Suppose: I have messages being stored in a single byte-stream file. These messages may come from multiple sources: the thermometer, the hygrometer, the barometer, etc. I can parse the byte stream into individual messages of the form, but it is not immediately known who the message is from.
The super-class is called generalMessage. It contains the methods for parsing the byte stream into individual messages, and storing the pieces that come in all of the messages. For example, if every message is of the form:
[startByte | Nbytes | MessageID | Time | Payload | checksum]
this suggests properties for each of the above sections of the message and methods to generate them.
Now, the MessageID tells me which one of the sources the message came from and thus how to interpret the payload. What I want to do is change my generalMessage object into a sub-class object of the appropriate type. Lets say thermoMessage. I want to recast my object into its sub-class and use the sub-class constructor to parse the payload. thermoMessage might just read a temperature (put that in the properties) when passed the payload, but I still want the super-class properties and methods to apply. At the end of the day, my thermometers message is a sub-class of more general messages.
How do I do this? Is there a way, short of "manually" looping through the properties and building a whole new object, to recast my super-class object into the associated sub-class?
One might also imagine this as a larger hierarchy; I may need a sub-sub-class to thermoMessage because I need different methods for different thermometers, something which may be hidden in the Payload. One might be a bespoke, perfectly calibrated wonder-thermometer, and the other built by some over-caffeinated grad-student who's preferred unit is "inches above the pencil mark", in which case specific methods would indeed be needed for each 'device'.
The above absurdity is, of course, just a stand-in, but it hopefully illustrates my question.
Thanks, - Dan

Respuesta aceptada

Matt J
Matt J el 14 de Abr. de 2017
Editada: Matt J el 14 de Abr. de 2017
The MathWorks-approved method for casting objects is apparently the one at this link.
So basically, yes, you have to loop through all the properties, but there is an easy automated way to do so using metaclasses.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by