views:

241

answers:

1

I've just found a strange error when deserializing from a ByteArray, where Vectors cannot contain types that extend Array: there is a TypeError when they are deserialized.

TypeError: Error #1034: Type Coercion failed: cannot convert []@4b8c42e1 to com.myapp.ArraySubclass.
    at flash.utils::ByteArray/readObject()
    at com.myapp::MyApplication()[/Users/aaaidan/MyApp/com/myapp/MyApplication.as:99]

Here's how:

public class Application extends Sprite {
    public function Application() {
        // register the custom class
        registerClassAlias("MyArraySubclass", MyArraySubclass);        

        // write a vector containing an array subclass to a byte array
        var vec:Vector.<MyArraySubclass> = new Vector.<MyArraySubclass>();
        var arraySubclass:MyArraySubclass = new MyArraySubclass();
        arraySubclass.customProperty = "foo";
        vec.push(arraySubclass);

        var ba:ByteArray = new ByteArray();
        ba.writeObject(arraySubclass);
        ba.position = 0;

        // read it back
        var arraySubclass2:MyArraySubclass = ba.readObject() as MyArraySubclass; // throws TypeError
    }
}

public class MyArraySubclass extends Array {
    public var customProperty:String = "default";
}

It's a pretty specific case, but it seems very odd to me. Anyone have any ideas what's causing it, or how it could be fixed?

+2  A: 

well, it seems array serialization is hardcoded. you should definitely post a bug report.

actually the code you posted doesn't throw an error since ba.readObject() as MyArraySubclass is simply null. MyArraySubclass(ba.readObject()) however would.

what you could try to fix it, would be to implement IExternalizable, altough I'm not sure it'll work any better.

I guess the problem is that Array is a very very special class in ActionScript (in the sense that in some way it is nothing more than any other dynamic class, but in other ways it's not at all) which leads to a lot of Array-specific code in the VM. Also, a question is, why do you need to subclass Array?

greetz

back2dos

back2dos
Hey, thanks for the answer. When you say that the code doesn't throw an error, I'd like to point out that it throws an error from _within_ the ByteArray's readObject method, not just from the Application class. So it's not the casting I've got there that's throwing the error, it's the deserialization... you know what I mean?
aaaidan
It's really odd, because it will deserialize fine, as long as it's not serialized within a Vector. I will file a bug, now you mention it... thanks for the support.
aaaidan