Trouble cloning an extended ByteArray

微笑、不失礼 提交于 2019-12-11 19:05:44

问题


I've extended the ByteArray class, like this:

[RemoteClass(alias="MyByteArray")]
public class MyByteArray extends ByteArray {}

and cloned an instance of this class using ByteArray#readObject()/writeObject(). However, for some reason, the cloned object is an instance of ByteArray rather than MyByteArray. This is illustrated in the following example:

registerClassAlias("MyByteArray", MyByteArray);
var b1:MyByteArray = new MyByteArray();
var tmp:ByteArray = new ByteArray();
tmp.writeObject(b1);           
tmp.position = 0;
var b2:* = tmp.readObject();
trace( b2 is MyByteArray ); // prints false
trace( b2 is ByteArray ); // prints true

Moreover, when I add some custom fields in MyByteArray class, they aren't saved with writeObject() and neither cloned...

Can anybody explain me why the cloned object is not an instance of MyByteArray?

Thanks a lot!


回答1:


I think this is because tmp is of type ByteArray, not of type MyByteArray. If you make tmp of type MyByteArray, it should return an object of the same type, using writeObject i think? Or you may need to typecast it.




回答2:


ByteArray is likely handled as a special case for object serialisation, so I doubt you'll get around it.

Attempting to subclass ByteArray sounds like a code smell to me. I'd look at using encapsulation rather than inheritance to solve your problem.



来源:https://stackoverflow.com/questions/875163/trouble-cloning-an-extended-bytearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!