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

조회 수: 4 (최근 30일)
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

채택된 답변

Matt J
Matt J 2017년 4월 14일
편집: Matt J 2017년 4월 14일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by